我之前做迷宫问题就比较偏向于dfs,因为容易想,就搜,撞到墙了就回到到上一步;但是用dfs会更快些;
当每条边的权重相等时,用dfs会比较快,因为它是一层一层的向外扩,所以第一次找到的终点即使到达的最短所需路径
迷宫问题:
给定一个 n×m 的二维整数数组,用来表示一个迷宫,数组中只包含 0 或 1,其中 0 表示可以走的路,1 表示不可通过的墙壁。
最初,有一个人位于左上角 (1,1) 处,已知该人每次可以向上、下、左、右任意一个方向移动一个位置。
请问,该人从左上角移动至右下角 (n,m) 处,至少需要移动多少次。
数据保证 (1,1) 处和 (n,m) 处的数字为 0,且一定至少存在一条通路。
输入格式
第一行包含两个整数 n 和 m。
接下来 n 行,每行包含 m 个整数(0 或 1),表示完整的二维数组迷宫。
输出格式
输出一个整数,表示从左上角移动至右下角的最少移动次数。
数据范围
1≤n,m≤100
dfs都是有个队列,只要队列不为空,就一直进行。我们初始将起点加入队列中,获取队列中对头t,遍历其上下左右四个方向如果可以走,并且如果该点没有被扫描过的,则将该点加入队列中,并将该点的距离写成t距起点的距离+1;如果我们再搜索过程中发现了终点,则直接返回终点据起点距离即可。(bfs是一层一层向外搜的,所以搜索到的点一定是距离起点最近的点)
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
typedef pair<int, int> PII;
const int N = 110;
int g[N][N], d[N][N];
PII q[N * N]; // 用数组模拟队列
int n, m;
void bfs() {
int hh = 1, tt = 1;
int dir[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
q[tt] = {1, 1};
memset(d, -1, sizeof d);
d[1][1] = 0;
while(hh <= tt) {
auto t = q[hh++];
for(int i = 0; i < 4; i++) {
int x = t.first + dir[i][0], y = t.second + dir[i][1];
if(x >= 1 && x <= n && y >= 1 && y <= m && g[x][y] == 0 && d[x][y] == -1) {
d[x][y] = d[t.first][t.second] + 1;
q[++tt] = {x, y};
}
}
}
}
int main() {
cin >> n >> m;
for(int i = 1; i <= n; i++)
for(int j = 1; j <= m; j++)
scanf("%d", &g[i][j]);
bfs();
printf("%d", d[n][m]);
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
现在,给你一个初始网格,请你求出得到正确排列至少需要进行多少次交换。
输入格式
输入占一行,将 3×3 的初始网格描绘出来。
例如,如果初始网格如下所示:
1 2 3
x 4 6
7 5 8
则输入为:1 2 3 x 4 6 7 5 8
输出格式
输出占一行,包含一个整数,表示最少交换次数。
如果不存在解决方案,则输出 −1。
该题有两个难点,也是常考点:
1.怎么表示此时的状态(map表示)
2.怎么算出和x交换位置的点的坐标(一维坐标,二维坐标互换)
也是bfs,首先将起始状态(字符串)加入队列中,map初始状态对应的距离为0;只要队列不为空,则执行以下操作:首先得到对头元素t,获取t中x的下标位置k,x = k % column.length, y = k % column.length;进行方向数组转换后看是否可以交换(不能为负,也不能越界)如果可以,则交换,查看map中是否有该状态,如没有则将该状态对应的距离 = t的距离+1,并且加入队列中,最后还原字符串(因为还有向下一次方向查找);如果在搜索过程中发现了终点状态,则直接返回。
#include <iostream>
#include <queue>
#include <unordered_map>
#include <string>
using namespace std;
int bfs(string st) {
string end = "12345678x";
int dirx[] = {-1, 1, 0, 0}, diry[] = {0, 0, -1, 1};
queue<string> q;
unordered_map<string, int> d;
q.push(st);
d[st] = 0;
while(q.size()) {
auto t = q.front();
q.pop();
int distance = d[t];
if(t == end) return distance;
//cout << t << endl;
int k = t.find('x');
int x = k / 3, y = k % 3;
for(int i = 0; i < 4; i++) {
int a = x + dirx[i];
int b = y + diry[i];
if(a >= 0 && a < 3 && b >= 0 && b < 3) {
swap(t[a * 3 + b], t[k]);
if(!d.count(t)) {
d[t] = distance + 1;
q.push(t);
}
swap(t[a * 3 + b], t[k]);
}
}
}
return -1;
}
int main() {
string st;
for(int i = 0; i < 9; i++) {
char c;
cin >> c;
st += c;
}
cout << bfs(st) << endl;
return 0;
}