之前写的东西因为断网没了(心态爆炸。。。)
总之用宽搜解决迷宫问题就是用队列先进先出的特点,一旦找到了结果一定是最短的(结合树状图自己理解)
代码如下
#include <iostream>
#include <queue>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <cstdio>
using namespace std;
bool vis[45][45];
char map[45][45];
int n, m;
struct node{
int x, y, step; //横纵坐标、到这个格子走了多少步
};
bool isok(int x, int y)
{
if (x >= 0 && x < n && y >= 0 && y < n && !vis[x][y])
return 1;
return 0;
}
int main()
{
while(scanf("%d%d",&n, &m) != EOF) {
for (int i = 0; i < n; ++i)
scanf("%s", map[i]); //绘制地图
memset(vis, 0, sizeof(vis));
for (int i = 0; i < n; ++i)
for (int j = 0; j < m; ++j)
if(map[i][j] == '#')
vis[i][j] = 1;
else
vis[i][j] = 0;
//初始化
queue<node> q;
node point, newpoint;
point.x = 0;
point.y = 0;
point.step = 1;
//队列登场!
q.push(point);
while(!q.empty()) {
point = q.front();
q.pop();
if(point.x == n-1&&point.y == m-1)
cout << point.step << endl; //找到了直接输出,因为宽搜出来的结果一定是最短的
for (int i = -1; i <= 1; ++i)
for (int j = -1; j <= 1; ++j)
if(abs(i)+abs(j) == 1 && isok(point.x + i, point.y + j) ) {
newpoint.x = point.x + i;
newpoint.y = point.y + j;
vis[newpoint.x][newpoint.y] = 1;
newpoint.step = point.step + 1;
q.push(newpoint);
}
}
}
return 0;
}
来源:https://www.cnblogs.com/xdaniel/p/12233049.html