【SSL 1455】电子老鼠闯迷宫【广搜 BFS模板】

Description

如下图12×12方格图,找出一条自入口(2,9)到出口(11,8)的最短路径。
在这里插入图片描述

Sample Input

12  //迷宫大小
2 9 11 8 //起点和终点
1 1 1 1 1 1 1 1 1 1 1 1  //邻接矩阵,0表示通,1表示不通
1 0 0 0 0 0 0 1 0 1 1 1
1 0 1 0 1 1 0 0 0 0 0 1
1 0 1 0 1 1 0 1 1 1 0 1
1 0 1 0 0 0 0 0 1 0 0 1
1 0 1 0 1 1 1 1 1 1 1 1
1 0 0 0 1 0 1 0 0 0 0 1
1 0 1 1 1 0 0 0 1 1 1 1
1 0 0 0 0 0 1 0 0 0 0 1
1 1 1 0 1 1 1 1 0 1 0 1
1 1 1 1 1 1 1 0 0 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1

Sample Output

(2,9)->(3,9)->(3,8)->(3,7)->(4,7)->(5,7)->(5,6)->(5,5)->(5,4)->(6,4)->(7,4)->(7,3)->(7,2)->(8,2)->(9,2)->(9,3)->(9,4)->(9,5)->(9,6)->(8,6)->(8,7)->(8,8)->(9,8)->(9,9)->(10,9)->(11,9)->(11,8)
27

分析&说明:

这道题也算是 广搜BFS的一道模板题。但注意题目要求输出遍历过的路径,所以要单独写一个输出函数。最少步数就是广搜模板

代码:

#include<iostream>
#include<cstdio>
using namespace std;
struct node{
	int x,y;
	//感觉结构体更舒服
}que[101];
int n,m,a[101][101],sx,sy,ex,ey;
int dx[5]={0,1,0,-1},s,dy[5]={-1,0,1,0},last,fa[101],vis[101][101];
int head,tail;
void print(int x){
    //输出函数
	if(x==0) return;
	s++;
	print(fa[x]);
	if(x!=last)
		printf("(%d,%d)->",que[x].x,que[x].y);
		//每次走的路径
	else
		printf("(%d,%d)\n",que[x].x,que[x].y);
}
void BFS_(){
    //广搜部分
	head=0;tail=1;
	que[1].x=sx;que[1].y=sy;
	while(head<tail){
		head++;
		for(int i=0;i<4;i++){
			int xx=dx[i]+que[head].x;
			int yy=dy[i]+que[head].y;
			if(xx>0&&xx<=n&&yy>0&&yy<=n&&a[xx][yy]==0&&vis[xx][yy]==0){
				tail++;
				fa[tail]=head;
				que[tail].x=que[head].x+dx[i];
				que[tail].y=que[head].y+dy[i];
				vis[que[tail].x][que[tail].y]=1;
				if(que[tail].x==ex&&que[tail].y==ey){
					s=0;
					last=tail;
					print(tail);
					cout<<s<<endl;
					tail=0;
					return;
				}
			}
		}
	}
}
int main()
{
	cin>>n;
	cin>>sx>>sy>>ex>>ey;
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=n;j++)
		{
			cin>>a[i][j];
		}
	}
	BFS_();
	return 0;
}
发布了37 篇原创文章 · 获赞 24 · 访问量 892

猜你喜欢

转载自blog.csdn.net/dgssl_xhy/article/details/103992245