给定一个n* m大小的迷宫,其中* 代表不可通过的墙壁,而“.”代表平地,S表示起点,T代表终点。
移动过程中,如果当前位置是(x, y)(下标从0开始),且每次只能前往上下左右、(x, y + 1)、(x, y - 1)、(x - 1, y)、(x + 1, y)四个位置的平地,求从起点S到达终点T的最少步数。
上面样例S为(2, 2),T的坐标为(4, 3)。
在本题中,由于求的是最少步数,而BFS是通过层次的顺序来遍历的,因此可以从起点S开始计数遍历的层数,那么在到达终点T时的层数就是需要求解的起点S到达终点T的最少步数。

.....
.*.*.
.*S* .
.*** .
...T*
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
const int maxn = 100;
int n, m;
char maze[maxn][maxn];
bool inq[maxn][maxn] = { false };
struct node {
int x;
int y;
int step;
}S,T,Node;
int X[4] = { 0,0,1,-1 };//建立增量数组方便遍历周边位置。
int Y[4] = { 1,-1,0,0 };
bool Isgo(int x, int y) {//判断位置是否有效
if (maze[x][y] == '*') return false;
else if (x >= n || x<0||y >= m||y<0||inq[x][y]==true) return false;//越界或者已经入过队。
else return true;
}
int BFS() {
queue<node> q;
q.push(S);
while (!q.empty()) {
node top = q.front();
q.pop();
if (top.x == T.x && top.y == T.y) {
return top.step;
}
for (int i = 0; i < 4; i++) { //易错:
//Node.X= top.x+X[i];
int newX = top.x + X[i];//这里应该建立两个整形变量用来判断新位置是否需要访问。 //Node.y=top.y+Y[i];
int newY = top.y + Y[i]; //if(Isgo(Node.x,Node.y)){
if (Isgo(newX, newY)) { //Node.step=top.step;
Node.step = top.step + 1; //q.push(NOde);
Node.x = newX; //inq[Node.x][Node.y]=ture
Node.y = newY;
q.push(Node);
inq[Node.x][Node.y] = true;
}
}
}
return -1;//没有找到返回一个-1;
}
int main() {
scanf("%d%d", &n, &m);
for (int i = 0; i < n; i++) {
getchar();//过滤掉每一行后面的换行符
for (int j = 0; j < m; j++) {
maze[i][j]=getchar();
}
maze[i][m + 1] = '\0';//不是使用scanf函数或者是gets函数,一定要在每个字符串的结尾处加'\0'。
}
scanf("%d%d%d%d", &S.x, &S.y, &T.x, &T.y);
S.step = 0;
printf("%d\n", BFS());
return 0;
}

最新文章

  1. 用Jenkins配置自动化构建
  2. 计蒜客 X的平方根
  3. 做一个MVC4的项目时留下的经验--增加IPrange
  4. java多态---ABC案列
  5. storm源代码分析---Transactional spouts
  6. 在JDBC中使用Java8的日期LocalDate、LocalDateTime
  7. 关于java线程中stop interrupt daemon wait notify
  8. servlet对象的生命周期
  9. out与ref以及可空类型用法的用法
  10. Android Studio 无法预览xml布局视图:failed to load AppCompat ActionBar with unkNown error
  11. Deflation Methods for Sparse PCA
  12. Collect devices information
  13. CSS3-字体渐变色
  14. Java ee第七周作业
  15. C语言第三讲,基本数据类型
  16. http请求的基本介绍
  17. Netty 能做什么
  18. 深入浅出JDBC-快速入门
  19. UDP传输原理及数据分片——学习笔记
  20. RESTful架构及SOA架构简单解析

热门文章

  1. 类属性和__init__的实例属性有何区别?进来了解一下吧
  2. django学习-12.访问不同url/接口地址实现对指定数据的增删改查功能
  3. C++算法代码——Tuna
  4. JVM元空间(Metaspace)
  5. 自关联映射:一个表自己关联自己,此时从同一个表中查询,通过起别名将一张表变成两张表,使用join语句。
  6. Oracle数据库的函数
  7. eclipse修改默认的代码注释
  8. SpringBoot(三):SpringBoot热部署插件
  9. 5G组网方案:NSA和SA
  10. go 在crontab里面运行报错 解决方案