标准广搜限制转弯次数
#include <stdio.h> #include <string.h> #include <queue> using namespace std; #define M 1002 struct node { int x,y,turn; node(int _x,int _y,int _turn) { x = _x; y = _y; turn = _turn; } }; int map[M][M],flag[M][M]; int move[4][2] = {-1,0,0,1,1,0,0,-1}; queue<node> q; int n,m; int judge(int x,int y) { if(x<1 || x>n || y<1 || y>m || map[x][y]) return 0; return 1; } int bfs(int x1,int y1,int x2,int y2) { memset(flag,0,sizeof(flag)); while(!q.empty()) { q.pop(); } q.push(node(x1,y1,0)); flag[x1][y1] = 1; while(!q.empty()) { int turn = q.front().turn; if(q.front().turn > 2) return 0; for(int i=0; i<4; i++) { int dx = q.front().x + move[i][0]; int dy = q.front().y + move[i][1]; while(judge(dx,dy) || dx == x2 && dy == y2) { if(dx == x2 && dy == y2 && map[dx][dy] == map[x1][y1]) return 1; if(!flag[dx][dy]) { flag[dx][dy] = 1; q.push(node(dx,dy,turn + 1)); } dx += move[i][0]; dy += move[i][1]; } } q.pop(); } return 0; } int main(int argc, char* argv[]) { #ifdef __MYLOCAL freopen("in.txt","r",stdin); #endif int q,x1,x2,y1,y2; while(scanf("%d%d",&n,&m) && n+m) { for(int i=1; i<=n; i++) { for(int j=1; j<=m; j++) scanf("%d",&map[i][j]); } scanf("%d",&q); while(q--) { scanf("%d%d%d%d",&x1,&y1,&x2,&y2); if(x1 == x2 && y1 == y2 || map[x1][y1] != map[x2][y2] || !map[x1][y1] || !map[x2][y2]) { printf("NO "); } else { printf("%s ",bfs(x1,y1,x2,y2) ? "YES" : "NO"); } } } return 0; }