C - Routing
思路
广搜或最短路板子。
搜一遍或跑一遍,求出 到 最少经过多少蓝色, 到 最少经过多少红色,相加即答案。这里给出最短路代码。
代码
#include <bits/stdc++.h>
using namespace std;
char s[505][505];
int n, b[505][505], r[505][505];
bool vis[505][505];
int xz[] = {1, 0, -1, 0};
int yz[] = {0, 1, 0, -1};
struct node {int x, y, d;};
bool operator < (node a, node b) {
return a.d > b.d;
}
priority_queue <node> q;
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i ++) scanf("%s", s[i] + 1);
memset(b, 0x3f, sizeof(b));
memset(r, 0x3f, sizeof(r));
b[1][1] = (s[1][1] == 'B');
q.push({1, 1, b[1][1]});
while (!q.empty()) {
node now = q.top(); q.pop();
if (vis[now.x][now.y]) continue;
vis[now.x][now.y] = 1;
if (now.x == n && now.y == n) continue;
for (int i = 0; i < 4; i ++) {
int xx = now.x + xz[i], yy = now.y + yz[i];
if (xx < 1 || xx > n || yy < 1 || yy > n) continue;
if (b[xx][yy] > now.d + (s[xx][yy] == 'B')) {
b[xx][yy] = now.d + (s[xx][yy] == 'B');
q.push({xx, yy, b[xx][yy]});
}
}
}
memset(vis, 0, sizeof(vis));
r[n][1] = (s[n][1] == 'R');
q.push({n, 1, r[n][1]});
while (!q.empty()) {
node now = q.top(); q.pop();
if (vis[now.x][now.y]) continue;
vis[now.x][now.y] = 1;
if (now.x == 1 && now.y == n) continue;
for (int i = 0; i < 4; i ++) {
int xx = now.x + xz[i], yy = now.y + yz[i];
if (xx < 1 || xx > n || yy < 1 || yy > n) continue;
if (r[xx][yy] > now.d + (s[xx][yy] == 'R')) {
r[xx][yy] = now.d + (s[xx][yy] == 'R');
q.push({xx, yy, r[xx][yy]});
}
}
}
printf("%d\n", b[n][n] + r[1][n]);
return 0;
}