问题描述
解题方法
BFS(广度优先搜索算法)
常用于迷宫类题目
代码展示
#include <bits/stdc++.h>
using namespace std;
const int maxn=50;//定义数组时用
//结构提记录位置和步数
struct node{
int x,y;//位置(x,y)
int step;//最小步数
}S,T,Node;// S为起点,T为终点,Node为临时结点
int n,m;//地图的行和列
char maze[maxn][maxn];//迷宫信息
bool inq[maxn][maxn]={false};//记录位置(x,y)是否已经入过队
int X[4]={1,0,0,-1}; //增量数组,上左右上并保证字典序最小
int Y[4]={0,-1,1,0};
//检测位置(x,y)是否有效
bool test(int x,int y){
if(x>=n||x<0||y>=m||y<0) return false;//超过边界
if(maze[x][y]=='1') return false;//墙壁
if(inq[x][y]== true) return false;//已入过队
return true; //有效位置
}
//广度优先搜索函数
int BFS(){
queue<node> q; //定义队列
q.push(S); //将起点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++){ //循环四次得到四个相邻位置
int newX=top.x+X[i];
int newY=top.y+Y[i];
if(test(newX,newY)){
//位置node的坐标是(newX,nodeY)
Node.x=newX;
Node.y=newY;
Node.step=top.step+1;//Node层数为top的层数加1
q.push(Node); //将结点Node加入队列
inq[newX][newY]=true; //设置位置(newX,newY)已入队
}
}
}
return -1;//无法到达T时返回-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("%d%d%d%d",&S.x,&S.y,&T.x,&T.y); //起点和终点的坐标
S.step=0;//起始化起点的层数为0,即S到S的最小步数为0
printf("%d\n",BFS());
return 0;
}
注意事项
1.本题只能求出最少步数
2.考试时可以记忆模板,加快解题速度