,水题啊。开始的时候还以为很难的。看了题解发现好多人都是用DFS。我是用BFS 的,跟1728比较像。
思路就是。一个方向搜到底。但是要注意的是有棋子的地方是不能经过的。
代码虐我千百遍,我待代码如初恋
Time Limit: 20000/10000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 18770 Accepted Submission(s): 4895
3 4 1 2 3 4 0 0 0 0 4 3 2 1 4 1 1 3 4 1 1 2 4 1 1 3 3 2 1 2 4 3 4 0 1 4 3 0 2 4 1 0 0 0 0 2 1 1 2 4 1 3 2 3 0 0
YES NO NO NO NO YES
#include <stdio.h> #include <stdlib.h> #include <malloc.h> #include <limits.h> #include <ctype.h> #include <string.h> #include <string> #include <math.h> #include <algorithm> #include <iostream> #include <queue> #include <stack> #include <deque> #include <vector> #include <set> using namespace std; #define MAXN 1000 + 10 int num[MAXN][MAXN]; int vis[MAXN][MAXN]; int n,m; int fx,fy; int xx[4]={-1,0,1,0}; int yy[4]={0,1,0,-1}; struct node{ int x; int y; int count; }; void BFS(int a,int b){ queue<node>q; node front; int i; node rear; front.x = a; front.y = b; front.count = -1; q.push(front); int mark = 0; while(!q.empty()){ front = q.front(); q.pop(); if(front.x==fx && front.y==fy){ if(front.count <= 2){ printf("YES\n"); mark = 1; break; } else{ printf("NO\n"); mark = 1; break; } } rear.count = front.count + 1; for(i=0;i<4;i++){ int dx = front.x + xx[i]; int dy = front.y + yy[i]; while((dx>=0&&dx<n&&dy>=0&&dy<m&&num[dx][dy]==0) || (dx>=0&&dx<n&&dy>=0&&dy<m&&dx==fx&&dy==fy)){ if(vis[dx][dy] == 0){ vis[dx][dy] = 1; rear.x = dx; rear.y = dy; q.push(rear); } dx = dx + xx[i]; dy = dy + yy[i]; } } } if(mark == 0){ printf("NO\n"); } } int main(){ int i,j; int k; int x1,y1,x2,y2; while(~scanf("%d%d",&n,&m)){ if(n==0 && m==0){ break; } memset(num,0,sizeof(num)); memset(vis,0,sizeof(vis)); for(i=0;i<n;i++){ for(j=0;j<m;j++){ scanf("%d",&num[i][j]); } } if(n==1 && m==1){ printf("NO\n"); continue; } scanf("%d",&k); while(k--){ scanf("%d%d%d%d",&x1,&y1,&x2,&y2); memset(vis,0,sizeof(vis)); vis[x1-1][y1-1] = 1; fx = x2-1; fy = y2-1; if(num[x1-1][y1-1] != num[x2-1][y2-1]){ printf("NO\n"); continue; } else if(num[x1-1][y1-1]==num[x2-1][y2-1] && num[x1-1][y1-1]==0){ printf("NO\n"); continue; } else{ BFS(x1-1,y1-1); } //BFS(x1-1,y1-1); } } return 0; }
原文地址:http://blog.csdn.net/zcr_7/article/details/39178145