每个格子看作一个点,相邻的同色格子连一条边,权值为0,相邻的异色格子连一条边,权值为1,
把无色格子拆成颜色不同的两个点,分别和无色格子相邻的有色格子相连,同色权值为2,异色权值为3
然后就是最短路问题啦
洛谷数据AC代码:
#include <iostream>
#include <queue>
#include <algorithm>
#include <utility>
#include <cstring>
using namespace std;
const int MAXM = 110;
const int INF = 0x3f3f3f3f;
int dx[4] = {1, -1, 0, 0};
int dy[4] = {0, 0, 1, -1};
int d[MAXM][MAXM][2], clr[MAXM][MAXM];
bool vis[MAXM][MAXM][2];
int m, n;
bool check_in(int x, int y)
{
return x >= 1 && y >= 1 && x <= m && y <= m;
}
typedef struct Node {
int x, y, d, c;
bool operator<(const Node &b) const{
return d > b.d;
}
Node(int x, int y, int d, int c) {
this->x = x;
this->y = y;
this->d = d;
this->c = c;
}
}Node;
priority_queue<Node> que;
int main()
{
cin >> m >> n;
memset(clr, -1, sizeof(clr));
for (int i = 0; i < n; i++) {
int x, y, c;
cin >> x >> y >> c;
clr[x][y] = c;
}
memset(d, 0x3f, sizeof(d));
d[1][1][clr[1][1]] = 0;
d[1][1][clr[1][1]^1] = INF;
que.push(Node(1,1,0,clr[1][1]));
int ans = -1;
while (!que.empty()) {
Node cur = que.top();
que.pop();
int cx = cur.x, cy = cur.y, cd = cur.d, cc = cur.c;
if (vis[cx][cy][cc])
continue;
vis[cx][cy][cc] = true;
d[cx][cy][cc] = cd;
//cout << "#" << cx << " " << cy << " " << cc << " " << cd << endl;
if (cx == m && cy == m) {
ans = cd;
break;
}
for (int i = 0; i < 4; i++) {
int tx = cx + dx[i];
int ty = cy + dy[i];
int tc = clr[tx][ty];
if (!check_in(tx, ty))
continue;
if (tc == -1) {
if (clr[cx][cy] != -1 && !vis[tx][ty][cc]) {
que.push(Node(tx, ty, cd+2, cc));
}
} else {
if (!vis[tx][ty][tc])
que.push(Node(tx, ty, cd+(tc^cc), tc));
}
}
}
cout << ans << endl;
return 0;
}
/*
3 3
1 1 1
2 2 1
3 3 1
:4
3 3
1 1 1
2 2 0
3 3 1
:6
3 5
1 1 1
1 3 0
2 2 1
3 1 1
3 3 1
*/