给定一个 n×m 的二维整数数组,用来表示一个迷宫,数组中只包含 0 或 1,其中 0 表示可以走的路,1 表示不可通过的墙壁。
最初,有一个人位于左上角 (1,1) 处,已知该人每次可以向上、下、左、右任意一个方向移动一个位置。
请问,该人从左上角移动至右下角 (n,m) 处,至少需要移动多少次。
数据保证 (1,1) 处和 (n,m) 处的数字为 0,且一定至少存在一条通路。
#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>
using namespace std;
typedef pair<int, int> PII;
const int N = 110;
int n, m;
int map[N][N];
int d[N][N]; // 每个点到原点的距离
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, -1, 0, 1};
int bfs() {
queue<PII> q;
memset(d, -1, sizeof d); // 将d初始化为-1
q.push({0, 0});
d[0][0] = 0;
while (!q.empty()) {
auto t = q.front();
q.pop();
int x = t.first, y = t.second;
for (int i = 0; i < 4; i ++ ) { // 遍历四个方向
int nx = x + dx[i], ny = y + dy[i];
if (nx >= 0 && nx < n && ny >= 0 && ny < m && map[nx][ny] == 0 && d[nx][ny] == -1) {
d[nx][ny] = d[x][y] + 1; // 为上个点的距离+1
q.push({nx, ny});
}
}
}
return d[n - 1][m - 1];
}
int main() {
cin >> n >> m;
for (int i = 0; i < n; i ++ )
for (int j = 0; j < m; j ++ )
cin >> map[i][j];
cout << bfs() << endl;
return 0;
}
八数码
在一个 3×3 的网格中,1∼8 这 8 个数字和一个 x 恰好不重不漏地分布在这 3×3 的网格中。
例如:
1 2 3
x 4 6
7 5 8
在游戏过程中,可以把 x 与其上、下、左、右四个方向之一的数字交换(如果存在)。
我们的目的是通过交换,使得网格变为如下排列(称为正确排列):
1 2 3
4 5 6
7 8 x
例如,示例中图形就可以通过让 x 先后与右、下、右三个方向的数字交换成功得到正确排列。
交换过程如下:
1 2 3 | 1 2 3 | 1 2 3 | 1 2 3
x 4 6 | 4 x 6 | 4 5 6 | 4 5 6
7 5 8 | 7 5 8 | 7 x 8 | 7 8 x
现在,给你一个初始网格,请你求出得到正确排列至少需要进行多少次交换。
#include <iostream>
#include <algorithm>
#include <queue>
#include <unordered_map>
using namespace std;
// map:基于红黑树,复杂度与树高相同,即O(logn)。
// unordered_map:基于散列表,复杂度依赖于散列函数产生的冲突多少,但大多数情况下其复杂度接近于O(1)。
const int N = 10;
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, -1, 0, 1};
int bfs(string s) {
queue<string> q; // 存储移动的状态
unordered_map<string, int> d; // 储存已处理过的状态步数
q.push(s);
d[s] = 0;
string end = "12345678x";
while (!q.empty()) {
auto t = q.front();
q.pop();
if(t == end) return d[end];
int is_x = t.find("x");
int x = is_x / 3, y = is_x % 3;
int distance = d[t];
for (int i = 0; i < 4; i ++ ) { // 遍历四个方向
int nx = x + dx[i], ny = y + dy[i];
if (nx >= 0 && nx < 3 && ny >= 0 && ny < 3) {
string tt = t;
swap(tt[is_x], tt[nx * 3 + ny]);
if(d.count(tt) == 0) { // 是否已经出现过
d[tt] = distance + 1;
q.push(tt);
}
}
}
}
return -1;
}
int main() {
char c;
string s;
for (int i = 0; i < 9; i ++ ) {
cin >> c;
s += c;
}
cout << bfs(s) << endl;
return 0;
}