Input
Output
Sample Input
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
Sample Output
YES NO NO NO NO YES
解析:这题和逃离迷宫的思路差不多,主要是用到了bfs ,和开一个vis数组来求出拐弯的次数,求出最少的拐弯次数,如果拐弯次数<3,就返回yes,否则返回yes。
注意:如果有一个点是0,就返回false,因为该点不可能连接。
#include <stdio.h> #include <string.h> #include <queue> using namespace std; const int INF = 0x3f3f3f; const int N = 1010; const int dr[] = {-1,1,0,0}; const int dc[] = {0,0,-1,1}; struct Node { int r; int c; Node(int r,int c) { this->r = r; this->c = c; } }; int grid[N][N]; int vis[N][N]; int n,m; bool bfs(int x1,int y1,int x2,int y2) { memset(vis,0,sizeof(vis)); queue<Node> q; vis[x1][y1] = 0; q.push(Node(x1,y1)); int r,c; while(!q.empty()) { Node front = q.front(); q.pop(); for(int i = 0; i < 4; i++) { r = front.r + dr[i]; c = front.c + dc[i]; while( r >= 0 && r < n && c >= 0 && c < m && (!grid[r][c] || (r == x2 && c == y2))) { if(!vis[r][c]) { vis[r][c] = vis[front.r][front.c] + 1; if(vis[r][c] > 3) { return false; } if(r == x2 && c == y2 && vis[r][c] <= 3) { return true; } q.push(Node(r,c)); } r += dr[i]; c += dc[i]; } } } return false; } bool judge(int x1,int y1,int x2,int y2) { if( x1 == x2 && y1 == y2) { return false; } if(!grid[x1][y1] || !grid[x2][y2]) { return false; } if(grid[x1][y1] != grid[x2][y2]) { return false; } int ok = bfs(x1,y1,x2,y2); if(ok) { return true; }else { return false; } } int main() { while(scanf("%d%d",&n,&m) != EOF && (n||m)) { memset(grid,0,sizeof(grid)); for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { scanf("%d",&grid[i][j]); } } int x1,y1,x2,y2; int t; scanf("%d",&t); bool ok; while(t--) { scanf("%d%d%d%d",&x1,&y1,&x2,&y2); x1--;y1--; x2--;y2--; ok = judge(x1,y1,x2,y2); if(ok) { printf("YES\n"); }else { printf("NO\n"); } } } return 0; }