P4554 小明的游戏https://www.luogu.com.cn/problem/P4554
#pragma warning(disable:4996)
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <unordered_map>
#include <queue>
#include <string>
#include <deque>
#include <cstring>
using namespace std;
int n, m;
char s[550][550];
int x1, y11, x2, y2;
struct node {
int x, y;
node(int x1=0,int y1=0):x(x1),y(y1) {
}
};
bool vis[550][550];
int d[550][550];
int go[4][2] = { {0,1},{1,0},{0,-1},{-1,0} };
void bfs() {
memset(d,0x3f,sizeof(d));
memset(vis,0,sizeof(vis));
d[x1][y11] = 0;
deque<node> q;
q.push_front(node(x1,y11));
while (!q.empty()) {
node t = q.front();
q.pop_front();
if (vis[t.x][t.y]) {
continue;
}
vis[t.x][t.y] = true;
for (int i = 0; i < 4;i++) {
int tx = t.x + go[i][0];
int ty = t.y + go[i][1];
if (tx>n||ty>m||tx<1||ty<1) {
continue;
}
int w = s[tx][ty] != s[t.x][t.y];
if (d[tx][ty]>d[t.x][t.y]+w) {
d[tx][ty] = d[t.x][t.y] + w;
if (w==0){
q.push_front(node(tx,ty));
}
else {
q.push_back(node(tx,ty));
}
}
}
}
printf("%d\n",d[x2][y2]);
}
int main() {
while (cin>>n>>m) {
if (n==0&&m==0) {
break;
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
scanf(" %c", &s[i][j]);
}
}
scanf("%d %d %d %d", &x1, &y11, &x2, &y2);
x1++, y11++, x2++, y2++;
bfs();
}
return 0;
}