【SSL1455】电子老鼠闯迷宫

Description

Description

如上图12×12方格图,找出一条自入口(2,9)到出口(11,8)的最短路径。

sample imput

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

分析

这题可以用两种方法解决:1.记忆化搜索 2.广搜
我这次选用广搜。直接铺开搜,套模板即可。嘿嘿,搞定!

最后上代码

#include<iostream>
#include<cstdio>
using namespace std;
int n,m,a[101][101],sx,sy,ex,ey,st[1001][3];
int dx[5]={0,0,1,0,-1},s,dy[5]={0,-1,0,1,0},last,fa[101];
int h,t;
void print(int x){
	if(x==0) return;
	s++;
	print(fa[x]);
	if(x!=last)
		printf("(%d,%d)->",st[x][1],st[x][2]);
	else
		printf("(%d,%d)\n",st[x][1],st[x][2]);
}
void bfs(){
	h=0;t=1;
	st[1][1]=sx;st[1][2]=sy;
	while(h<t){
		h++;
		for(int i=1;i<=4;i++){
			int xx=dx[i]+st[h][1];
			int yy=dy[i]+st[h][2];
			if(xx>0&&xx<=n&&yy>0&&yy<=n&&a[xx][yy]==0){
				t++;
				fa[t]=h;
				st[t][1]=xx;
				st[t][2]=yy;
				a[xx][yy]=1;
				if(st[t][1]==ex&&st[t][2]==ey){
					s=0;
					last=t;
					print(t);
					cout<<s;
					t=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;
}
发布了31 篇原创文章 · 获赞 23 · 访问量 914

猜你喜欢

转载自blog.csdn.net/dglyr/article/details/103390275