知识点:双端队列,广搜
这个题第一次做的时候会觉得有点新,尤其是这种模型,要看出来它是01最短路是问题的关键也是最难的,首先这个题我们每次可以从一个点扩展的点不是原来的上下左右,而是另外4个方向,这个是首先要注意到的,然后注意到地图里面有类似桥梁的东西,我们想往某个方向走,如果那个对应位置的桥梁是对应的形状,那么就不耗费,也就是距离是0,也就是状态扩展的代价是0,如果那个方向对应那个位置的桥梁形状不对,代价是1,也就是距离是1,所以抽象出来了01最短路的模型,这个01最短路问题有一个专门的算法是线性的,也就是双端队列BFS,直接套就行了
#include <bits/stdc++.h>
using namespace std;
const int N = 505;
struct node {
int x, y, step;
node() {}
node(int a, int b, int c): x(a), y(b), step(c) {}
};
int n, m, vis[N][N];
int dx[4] = {-1, -1, 1, 1};
int dy[4] = {-1, 1, 1, -1};
int dh[4] = {-1, -1, 0, 0};
int dw[4] = {-1, 0, 0, -1};
char s[N][N];
char str[10] = "\\/\\/";
void bfs() {
deque<node> q;
q.push_back(node(0, 0, 0));
while (!q.empty()) {
node now = q.front(); q.pop_front();
if (now.x == n && now.y == m) {
cout << now.step;
return;
}
if (vis[now.x][now.y]) continue;
vis[now.x][now.y] = 1;
for (int i = 0; i < 4; i++) {
int x1 = now.x + dx[i];
int y1 = now.y + dy[i];
if (x1 < 0 || x1 > n || y1 < 0 || y1 > m) continue;
int x2 = now.x + dh[i];
int y2 = now.y + dw[i];
if (s[x2][y2] == str[i]) {
q.push_front(node(x1, y1, now.step));
} else {
q.push_back(node(x1, y1, now.step + 1));
}
}
}
cout << "NO SOLUTION";
}
int main() {
cin >> n >> m;
for (int i = 0; i < n; i++) {
scanf("%s", s[i]);
}
bfs();
return 0;
}