题目链接源自zoj
我的代码如下:
#include <iostream>
#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;
struct node
{
int x, y, t;
};
const int MAX = 1e6 + 1;
int n, m;
int maze[MAX] = { 0 };
queue<node>q;
queue<node>null;
bool f = false;
int s1, s2, f1, f2;
bool book[MAX] = { 0 };
node bfs(int x, int y)
{
node p{ x,y,0 };
q = null; q.push(p);
while (!q.empty())
{
node pp = q.front(); q.pop();
if (pp.x == f1 && pp.y == f2) { f = true; p = pp; break; }
if (pp.x<1 || pp.x>n || pp.y<1 || pp.y>m) continue;
//cout << "P :" << pp.x << " " << p.y << " " << pp.t << endl;
if ((maze[pp.x* m +pp.y] + pp.t)&1 && !book[pp.x* m +pp.y])
{
q.push({ pp.x,pp.y + 1,pp.t + 1 }); q.push({ pp.x,pp.y - 1,pp.t + 1 });
}
if (!((maze[pp.x* m +pp.y] + pp.t) & 1) && !book[pp.x* m +pp.y])
{
q.push({ pp.x+ 1,pp.y ,pp.t + 1 }); q.push({ pp.x- 1,pp.y ,pp.t + 1 });
}
book[pp.x* m +pp.y] = true;
}
if (f) return p;
else return {0,0,-1};
}
int main()
{
int t; cin >> t;
while (t--)
{
f = false;
memset(book, 0, sizeof(book));
scanf_s("%d%d", &n, &m);
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
{
scanf_s("%d", &maze[i * m+j]);
}
}
cin >> s1 >> s2 >> f1 >> f2;
node p = bfs(s1, s2);
//cout << "f " << f << endl;
if (f) cout << p.t << endl;
else cout << -1 << endl;
}
return 0;
}
最后,我不会代码高亮,如果有大佬路过,烦请赐教。