3 4<br>1 2 3 4<br>0 0 0 0<br>4 3 2 1<br>4<br>1 1 3 4<br>1 1 2 4<br>1 1 3 3<br>2 1 2 4<br>3 4<br>0 1 4 3<br>0 2 4 1<br>0 0 0 0<br>2<br>1 1 2 4<br>1 3 2 3<br>0 0<br>
YES<br>NO<br>NO<br>NO<br>NO<br>YES<br>
思路:相判断(x1,y1) (x2,y2)位置上的数是否相同,若不同或都为0,直接输出“NO”,否则,从(x1,y1)位置开始bfs搜索,若能检索到(x2,y2)位置则“YES”,否则“NO”
检索时只走为0 的点,走后标记。
刚开始的时候,忘记记录转折次数了。
这道题是不是有点问题,必须得按照一定顺序压入队列才行,我刚开始的压入顺序是:下、上、左、右 怎么都通不过,
然后改成:右、下、左、上 就过了,求原因。
AC代码:
#include<iostream>
#include<string.h>
#include<stdlib.h>
#include<algorithm>
#include<queue>
using namespace std;
int cb1[1000][1000];
int cb[1000][1000];
struct point
{
int x, y;
int flag;
char ch;
};
bool bfs(int x1, int y1, int x2, int y2, int n, int m, int cb[1000][1000])
{
point a, b;
a.x = x1; a.y = y1; a.flag = 0; a.ch = '0';
b.x = x2; b.y = y2; b.flag = 0; b.ch = '0';
queue<point>Q;
Q.push(a);
while (!Q.empty())
{
point p = Q.front();
Q.pop();
if (p.x == b.x&&p.y == b.y)
return true;
if (p.y + 1 <= m)
{
if (p.x == b.x&&p.y + 1 == b.y)
{
if (p.flag<3)
return true;
else
{
if (p.ch == '4')
return true;
}
}
else
{
if (cb[p.x][p.y + 1] == 0)
{
point c;
c.x = p.x;
c.y = p.y + 1;
if (p.ch != '4')
c.flag = p.flag + 1;
else c.flag = p.flag;
c.ch = '4';
if (c.flag < 4)
{
Q.push(c);
cb[p.x][p.y + 1] = -1;
}
}
}
}
if (p.x + 1 <= n)
{
if (p.x + 1 == b.x&&p.y == b.y)
{
if (p.flag<3)
return true;
else
{
if (p.ch == '2')
return true;
}
}
else
{
if (cb[p.x + 1][p.y] == 0)
{
point c;
c.x = p.x + 1;
c.y = p.y;
if (p.ch != '2')
c.flag = p.flag + 1;
else c.flag = p.flag;
c.ch = '2';
if (c.flag < 4)
{
Q.push(c);
cb[p.x + 1][p.y] = -1;
}
}
}
}
if (p.y - 1 > 0)
{
if (p.x == b.x&&p.y - 1 == b.y)
{
if (p.flag<3)
return true;
else
{
if (p.ch == '3')
return true;
}
}
else
if (cb[p.x][p.y - 1] == 0)
{
point c;
c.x = p.x;
c.y = p.y - 1;
if (p.ch != '3')
c.flag = p.flag + 1;
else c.flag = p.flag;
c.ch = '3';
if (c.flag < 4)
{
Q.push(c);
cb[p.x][p.y - 1] = -1;
}
}
}
if (p.x - 1 > 0)
{
if (p.x - 1 == b.x&&p.y == b.y)
{
if (p.flag<3)
return true;
else
{
if (p.ch == '1')
return true;
}
}
else
if (cb[p.x - 1][p.y] == 0)
{
point c;
c.x = p.x - 1;
c.y = p.y;
if (p.ch != '1')
c.flag = p.flag + 1;
else c.flag = p.flag;
c.ch = '1';
if (c.flag < 4)
{
Q.push(c);
cb[p.x - 1][p.y] = -1;
}
}
}
}
return false;
}
int main()
{
int m, n;
memset(cb, 0, sizeof(cb));
while (cin >> n >> m)
{
if (m == 0 && n == 0)
break;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
{
cin >> cb1[i][j];
}
int q;
cin >> q;
for (int i = 0; i < q; i++)
{
int x1, x2, y1, y2;
cin >> x1 >> y1 >> x2 >> y2;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
{
cb[i][j] = cb1[i][j];
}
if (cb1[x1][y1] != cb1[x2][y2])
cout << "NO" << endl;
else
{
if (cb1[x1][y1] == 0 && cb1[x2][y2] == 0)
cout << "NO" << endl;
else if (x1 == x2&&y1 == y2)
cout << "NO" << endl;
else
{
if (bfs(x1, y1, x2, y2, n, m, cb))
cout << "YES" << endl;
else cout << "NO" << endl;
}
}
}
}
system("pause");
return 0;
}