代码如下
#include <bits/stdc++.h>
using namespace std;
const int mx[4] = {0, 0, 1, -1};
const int my[4] = {1, -1, 0, 0};
int n, m;
int sx, sy, ex, ey;
int mv[500][500];
int mmap[500][500];
void bfs(pair<int, int> s) {
queue<pair<int, int> > q;
q.push(s);
mv[s.first][s.second] = 0;
while(!q.empty()) {
int x = q.front().first, y = q.front().second, tx, ty, vv;
q.pop();
for(int i = 0; i < 4; ++i) {
tx = mx[i] + x, ty = my[i] + y;
if(tx < 0 || tx > n - 1 || ty < 0 || ty > n - 1)
continue;
vv = mv[x][y] + (mmap[x][y] ^ mmap[tx][ty]);
//cout << x << " " << " " << y << " " << vv << endl;
if(vv < mv[tx][ty]) {
mv[tx][ty] = vv;
q.push(make_pair(tx, ty));
}
}
}
}
int main() {
while(1) {
memset(mv, 0x3f, sizeof(mv));
memset(mmap, 0, sizeof(mmap));
scanf("%d%d", &n, &m);
if(n == 0 && m == 0)
break;
char ch[505];
for(int i = 0; i < n; ++i) {
scanf("%s", ch);
for(int j = 0; j < m; ++j) {
if(ch[j] == '#')
mmap[i][j] = 1;
else
mmap[i][j] = 0;
}
}
scanf("%d%d%d%d", &sx, &sy, &ex, &ey);
bfs(make_pair(sx, sy));
printf("%d\n", mv[ex][ey]);
}
return 0;
}
提交记录
谢谢各位大佬