常见迷宫:

输入迷宫 启点 终点 然后求最短路径 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)

最新文章

  1. shiro的使用2 灵活使用shiro的密码服务模块
  2. android App使用新浪微博sdk的使用总结
  3. BZOJ 3211 题解
  4. mysql列属性auto(mysql笔记四)
  5. C# socket 实现消息中心向消息平台 转发消息 (修改)
  6. 执行umount 命令的时候出现 device is busy
  7. Android Layout_Gravity和Gravity
  8. Apache Mina 2.x 框架+源码分析
  9. asp.net+Sqlserver 通过存储过程读取数据
  10. ios设置音乐audio自动播放
  11. Java之二分查找算法
  12. LeetCode - 刷题经验
  13. ASP.NET Core Web API 索引 (更新Redis in .NET Core)
  14. tinyxml2使用
  15. WordPress引入css/js两种方法
  16. c# 使用 HttpWebRequest模拟登陆(附带验证码)
  17. HDU 4370 0 or 1(转化为最短路)题解
  18. 学习blus老师js(6)--js运动基础
  19. 【转】GitHub汉化脚本(谷歌浏览器)
  20. Python 爬虫之 Scrapy 分布式原理以及部署

热门文章

  1. 2016/10/29 action与form表单的结合使用
  2. linux安装glassfish并布署
  3. fix for 12c profile
  4. sed与正则表达式
  5. Ubuntu14.04环境下java web运行环境搭建
  6. (转)SpringMVC学习(十一)——SpringMVC实现Resultful服务
  7. JAVA基础——IO流字符流
  8. 通俗易懂的Redux了解下
  9. js 随机生成颜色
  10. gulp 前缀