简单宽搜 迷宫问题 BFS计步

时间:2022-05-07 15:43:56

在一个M×N的迷宫中,找出最短路径离开迷宫。

' S ':起点;' G ':终点;' # ':墙壁;’ . ‘:路

For example:

Input:

10 11
#S########
#.######.#
......#..#
.#.##.##.#
.#........
##.##.####
....#....#
.#######.#
....#.....
.####.###.
....#...G#

Output:

23

宽搜+计步解决。

#include<cstdio>
#include<queue>
using namespace std;
int bfs(char map[101][101],int m,int n,int i,int j,int count[]);
int main()
{
int m,n,i,j,count[10000]={};
char map[101][101];
while(scanf("%d %d",&m,&n)!=EOF)
{
for(i=0;i<n;i++)
scanf("%s",&map[i]);
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
if(map[i][j]=='S')
break;
if(map[i][j]=='S')
break;
}
printf("%d\n",bfs(map,m,n,i,j,count));
}
return 0;
}
int bfs(char map[101][101],int m,int n,int i,int j,int count[])
{
char *p;
int num=0,num2=0,k=0;
count[k]=1;
queue<char*>que;
que.push(&map[i][j]);
while(1)
{
p=que.front();
que.pop();
count[k]--;
if(*p=='G')
break;
*p='#'; //标记访问过
if(p-101>=&map[0][0]&&(*(p-101)=='.'||*(p-101)=='G')) //检索四周入队列
que.push(p-101),count[k+1]++;
if(p+101<=&map[n-1][m-1]&&(*(p+101)=='.'||*(p+101)=='G'))
que.push(p+101),count[k+1]++;
if(p+1<=&map[(p-&map[0][0])/101][m-1]&&(*(p+1)=='.'||*(p+1)=='G'))
que.push(p+1),count[k+1]++;
if(p-1>=&map[(p-&map[0][0])/101][0]&&(*(p-1)=='.'||*(p-1)=='G'))
que.push(p-1),count[k+1]++;
if( count[k]==0) //计数
num++,k++;
}
return num;
}