这一题,做了好久,终于AC了,感觉题目有点坑,唉,题目不是很难,就是坑!!~~
找一个错误,找了半天,后来才看到是变量用错了!!~
题目中的b数组是标记数组。
#include <iostream>
#include <cstdio>
#include <queue>
using namespace std;
#define INF 1000000
int xy[4][2] = { { -1 , 0 } , { 1 , 0 } , { 0 , -1 } , { 0 , 1 } };
int m, n;
int x1, x2, y1, y2;
int a[1005][1005], b[1005][1005];
class data
{
public:
int x, y;
int k, dir; //k为转弯数,dir是方向
};
int bfs()
{
if((x1 == x2 && y1 == y2) || (a[x1][y1] != a[x2][y2]) || !a[x1][y1] || !a[x2][y2])
return 0;
queue <data> que;
data te, temp;
te.x = x1; te.y = y1;
te.k = 0; te.dir = -1;
que.push(te);
b[te.x][te.y] = 0;
while(!que.empty())
{
temp = que.front();
que.pop();
if(temp.x == x2 && temp.y == y2)
return 1;
for(int k = 0; k < 4; k++)
{
te.x = temp.x + xy[k][0];
te.y = temp.y + xy[k][1];
if(temp.dir < 0)
{
te.dir = k;
te.k = 0;
}
else if(temp.dir == k)
{
te.dir = temp.dir;
te.k = temp.k;
}
else
{
te.dir = k;
te.k = temp.k + 1;
}
if(te.x >= 1 && te.x <= m && te.y >= 1 && te.y <= n && te.k <= 2 && te.k <= b[te.x][te.y]) //判断是否符合
{
if(a[te.x][te.y] == 0 || (te.x == x2 && te.y == y2)) //判断是否为零或者到终点
{
b[te.x][te.y] = te.k;
que.push(te);
}
}
}
}
return 0;
}
int main()
{
int i, j, num;
while(scanf("%d%d", &m, &n) != EOF)
{
if(m == 0 && n == 0)
break;
for(i = 1; i <= m; i++)
{
for(j = 1; j <= n; j++)
scanf("%d", &a[i][j]);
}
scanf("%d", &num);
while(num--)
{
scanf("%d%d%d%d", &x1, &y1, &x2, &y2);
for(i = 0; i <= m; i++)
{
for(j = 0; j <= n; j++)
b[i][j] = INF;
}
if(bfs())
printf("YES\n");
else
printf("NO\n");
}
}
return 0;
}