BFS简单迷宫
2024-10-19 18:38:57
常见迷宫:
输入迷宫 启点 终点 然后求最短路径 BFS例题
用dist[][]数组来记录 启点到每个点的最短路径
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <string.h>
#include <queue>
using namespace std; const int maxsize = ;
const int INF = 0xfff3;
int m,n;
int d[][] = { {-, , , }, {, , , -} };
int dist[maxsize][maxsize];//书上方法 : 用dist[m][n]将最短路径储存起来 初始为INF表示无法到达
struct Pos
{
int x,y;
}st,ed;
char maze[maxsize][maxsize]; bool check(int x, int y)
{
if(x < || x >= m || y < || y >= n) return false;
if(maze[x][y] == '#' || dist[x][y] != INF) return false;//!=INF表示可达就已经走到过
return true;
}
int bfs()
{
for (int i = ; i < m; i++)
for (int j = ;j < n; j++)
dist[i][j] = INF;
queue<struct Pos> que;
que.push(st);
dist[st.x][st.y] = ;//自己到自己为0
while (!que.empty())
{
int nx, ny;
Pos node = que.front();
que.pop();
//ans ++;//这里出错 并不是 每次出队都是最短路径中的结点 调试可以发现
if(node.x == ed.x && node.y == ed.y) return dist[ed.x][ed.y];
for (int i = ; i < ; i++)
{
nx = node.x + d[][i];
ny = node.y + d[][i];
if (check(nx, ny))
{
Pos temp;
temp.x = nx;
temp.y = ny;//这里用pair更好 方便
dist[nx][ny] = dist[node.x][node.y] + ;
que.push(temp);
}
}
}
return -;
} int main()
{
ifstream cin("in.txt");
freopen("in.txt", "r", stdin);
scanf("%d%d", &m, &n);
getchar();
for (int i = ;i < m; i++)
{
gets(maze[i]);
}
for (int i = ; i < m; i++)
{
for (int j = ; j < n; j++)
{
if (maze[i][j] == 'S')
{
st.x = i;
st.y = j;
}
if (maze[i][j] == 'G')
{
ed.x = i;
ed.y = j;
}
}
}
int ans = bfs();
if (ans == -) cout << "no way" << endl;
else cout << ans << endl;
}
//对fill 和 memset 还需了解 是在不行就循环填充
//用dist记录最短路径 而不是每一次出队ans++
//时间复杂度 状态转移是四个方向 每个格至多访问一次 O(4*m*n)
最新文章
- shiro的使用2 灵活使用shiro的密码服务模块
- android App使用新浪微博sdk的使用总结
- BZOJ 3211 题解
- mysql列属性auto(mysql笔记四)
- C# socket 实现消息中心向消息平台 转发消息 (修改)
- 执行umount 命令的时候出现 device is busy
- Android Layout_Gravity和Gravity
- Apache Mina 2.x 框架+源码分析
- asp.net+Sqlserver 通过存储过程读取数据
- ios设置音乐audio自动播放
- Java之二分查找算法
- LeetCode - 刷题经验
- ASP.NET Core Web API 索引 (更新Redis in .NET Core)
- tinyxml2使用
- WordPress引入css/js两种方法
- c# 使用 HttpWebRequest模拟登陆(附带验证码)
- HDU 4370 0 or 1(转化为最短路)题解
- 学习blus老师js(6)--js运动基础
- 【转】GitHub汉化脚本(谷歌浏览器)
- Python 爬虫之 Scrapy 分布式原理以及部署