题是中文..
题目链接:
点击打开链接
代码:
#include<iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
int n,m;
int grid[1005][1005];
bool vis[1005][1005];
int mov[4][2] = {{0,1},{0,-1},{1,0},{-1,0}};
struct node{
int r,c;
int dir;
int cnt;
};
bool bfs(int sr,int sc,int er,int ec){
queue<node> q;
node t1,t2;
t1.r = sr; t1.c = sc;
t1.dir = -1;
t1.cnt = 0;
q.push(t1);
while(!q.empty()){
t1 = q.front();
q.pop();
if(t1.r==er && t1.c==ec){
return true;
}
for(int i=0; i<4; i++){
t2.r = t1.r + mov[i][0];
t2.c = t1.c + mov[i][1];
if(t2.r<=n && t2.r>0 && t2.c<=m && t2.c>0 && (grid[t2.r][t2.c]==0||(t2.r==er && t2.c==ec)) && vis[t2.r][t2.c]==false){
t2.dir = i;
t2.cnt = t1.cnt;
if(t1.dir!=-1 && t2.dir!=t1.dir) t2.cnt++;
if(t2.cnt<=2) { //这里理解为只找最多转折两次的路径,如果到最后判断cnt会有有一些点vis已经设置成true的问题
q.push(t2);
vis[t2.r][t2.c] = true;
}
}
}
}
return false;
}
int main(){
int i,j,q,x1,y1,x2,y2;
while(scanf("%d%d",&n,&m)!=EOF){
if(n==0 && m==0) break;
for(i=1; i<=n; i++){
for(j=1; j<=m; j++){
scanf("%d",&grid[i][j]);
}
}
scanf("%d",&q);
while(q--){
scanf("%d%d%d%d",&x1,&y1,&x2,&y2);
if((grid[x1][y1]!=grid[x2][y2])||(grid[x1][y1]==0 && grid[x2][y2]==0)){
printf("NO\n");
continue;
}
memset(vis,false,sizeof(vis));
if(bfs(x1,y1,x2,y2)) printf("YES\n");
else printf("NO\n");
}
}
return 0;
}