说明
一个迷宫由R行C列格子组成,有的格子里有障碍物,不能走;有的格子是空地,可以走。
给定一个迷宫,求从左上角走到右下角最少需要走多少步(数据保证一定能走到)。只能在水平方向或垂直方向走,不能斜着走。
输入格式
第一行是两个整数,R和C,代表迷宫的行数和列数。( 1<= R,C <= 40)
接下来是R行,每行C个字符,代表整个迷宫。空地格子用'.'表示,有障碍物的格子用'#'表示。迷宫左上角和右下角都是'.'。
输出格式
输出从左上角走到右下角至少要经过多少步(即至少要经过多少个空地格子)。计算步数要包括起点和终点。
样例
输入数据 1
5 5
..###
#....
#.#.#
#.#.#
#.#..
Copy
输出数据 1
9
bfs模板题
反思总结:
1、队列的队首是 fornt
2、当入队列的是结构体的时候,记得使用中括号 { } 把结构体的变量括起来入队。
如:q . push ( { x , y , step } ) ;
3、谨慎的使用 i++ 或 ++i 的形式,一个是读变量后++,一个是先 ++ 后读变量。
这道题中,步数(step):
如果使用 step++ 程序会出现错误,答案有误。
如果使用 ++step 则会出现结果比程序运行的多 1 。
如果使用 step + 1 ,结果与程序运行的一样。
#include <stdio.h>
#include <math.h>
#include <algorithm>
#include <iostream>
#include <string.h>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <vector>
using namespace std;
int n,m;
char a[45][45];
int vis[45][45];
struct temp {
int tx;
int ty;
int step;
};
int nx[4]= {0,0,1,-1};
int ny[4]= {1,-1,0,0};
queue<temp> q;
void bfs() {
while(!q.empty()) {
temp t=q.front();
q.pop();
if(t.tx==n-1&&t.ty==m-1) {
cout<<t.step;
return;
}
if(vis[t.tx][t.ty])
continue;
vis[t.tx][t.ty]=1;
for(int i=0; i<4; i++) {
int x=t.tx+nx[i],y=t.ty+ny[i];
if(x>=0&&y>=0&&x<n&&y<m&&vis[x][y]==0&&a[x][y]=='.')
q.push({x,y,t.step+1});
}
}
}
int main() {
scanf("%d%d",&n,&m);
for(int i=0; i<n; i++) {
cin>>a[i];
}
q.push({0,0,1});
bfs();
return 0;
}