【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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章