小记:这题起初没仔细分析方向的问题,导致了wa几次,然后又是同一方向搜过来的,但是转弯的次数要少的这点没管。
思路:这题很明显可以看出是bfs, 但是处理起来会稍微麻烦点,
1、我们对两个点首先判是否值一样大,这样才能消。再看是否不是0,因为空的话,你也不能消。
2、开始bfs,我们从其中一点开始bfs。每点可以往上下左右4个方向搜,因为bfs都会有标记的,用以判重。而这里的标记就很重要
3、我们以当前这点是从哪个方向搜过来的来判重,三维[x][y][dir], dir为方向,只要5即可。所以空间还是够的。
4、vis[x][y][dir]用来标记从dir这个方向过来的是否搜过,而这里也是我之前错的一点,我没有管同一个方向搜过来的转弯次数少的,
5、所以为了保证答案的正确性,我用vis来标记这个方向的当前最少的转弯次数,小于这个的,虽然你是同一个方向过来的,但是还是拒绝让你再去搜了。
6、我们搜的点都必须是0,即空的地方。然后再是越界判断,再是方向的判断
7、方向的判断之前我也出错了,即我当前要往某一个方向(i) 搜的时候,这个方向和我来的方向(dir)是否是转过一个弯的,这里想通了就比较简单,动手划一下即可,
8、首先不能往回搜,(dir+2)%4 ==i 就是来到当前点的之前的点的方向(我是上0左1下2右3,用以表示方向)。然后 dir != i就表示转了个弯,细细思考还是比较简单的
至此代码写起来应该就简单了
代码:
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <map>
#include <set>
#include <vector>
#include <stack>
#include <queue>
#include <algorithm>
using namespace std;
#define mst(a,b) memset(a,b,sizeof(a))
#define REP(a,b,c) for(int a = b; a < c; ++a)
#define eps 10e-8
const int MAX_ = 1010;
const int N = 100010;
const int INF = 0x7fffffff;
struct Point {
int x, y;
int ch;//转弯的次数
int d;
}p2;
int dir[4][2] = {{0,-1},{-1,0},{0,1},{1,0}};
int vis[MAX_][MAX_][5];
int a[MAX_][MAX_], num[MAX_][MAX_];
int n, m;
int bfs(Point x)
{
queue<Point> q;
x.ch = 0;
x.d = -1;
q.push(x);
REP(i , 0 , 5){
vis[x.x][x.y][i] = 1;
}
while(!q.empty()){
Point cur = q.front(); q.pop();
if(cur.x == p2.x && cur.y == p2.y){
return 1;
}
else if(a[cur.x][cur.y] != 0)continue;
REP(i,0,4){
Point nt;
nt.x = cur.x + dir[i][1];
nt.y = cur.y + dir[i][0];
nt.ch = cur.ch;
if((nt.x > 0 && nt.x <= n) &&(nt.y > 0 && nt.y <= m) ){
if(cur.d == -1)nt.ch = 0;
else if((cur.d + 2)%4 == i){continue;}
else if(cur.d != i ){
++nt.ch;
}
if(nt.ch > 2) continue;
nt.d = i;
if(!vis[nt.x][nt.y][nt.d+1] || nt.ch+1 < vis[nt.x][nt.y][nt.d+1]){
vis[nt.x][nt.y][nt.d+1] = nt.ch+1;
q.push(nt);
}
}
}
}
return 0;
}
int main(){
int T, k;
while(~scanf("%d%d", &n, &m), n||m){
REP(i, 1, n+1)REP(j, 1, m+1){
scanf("%d", &a[i][j]);
}
scanf("%d", &k);
Point p1;
REP(i, 0, k){
scanf("%d%d%d%d", &p1.x, &p1.y, &p2.x, &p2.y);
mst(vis, 0);
int ans;
if(a[p1.x][p1.y] != a[p2.x][p2.y] || a[p1.x][p1.y] == 0){
ans = 0;
}else {
int tmp = a[p1.x][p1.y];
a[p1.x][p1.y] = 0;
ans = bfs(p1);
a[p1.x][p1.y] = tmp;
}
if(ans){
printf("YES\n");
}else {
printf("NO\n");
}
}
}
return 0;
}