【SSL_1455】电子老鼠闯迷宫

电子老鼠闯迷宫

Time Limit:1000MS Memory Limit:65536K
Total Submit:272 Accepted:180

Description

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

Input

Output

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 1 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

思路

用广搜寻找最短路径

代码

#include<iostream>
#include<algorithm>
#include<cstdio>
using namespace std;
long long n,sx,sy,ex,ey,a[51][51],c[51][51],s,head,tail,fx[4][2]={{1,0},{0,1},{-1,0},{0,-1}};
struct haha{
	int fa;
	int x;
	int y;
}b[2501];
void in(){
	//输入迷宫
	cin>>n>>sx>>sy>>ex>>ey;
	for(int i=1;i<=n;i++){
		for(int j=1;j<=n;j++){
			cin>>a[i][j];
		}
	}
}
bool check(int x,int y){ 
	//check检查是否可以往这个方向走
	if(x<1||y<1||x>n||y>n) return 0;
	if(c[x][y]) return 0;
	if(a[x][y]) return 0;
	return 1;
}
void ct(int t){ //递归回去输出路径
	if(b[t].x==sx&&b[t].y==sy){
		s++;
		cout<<"("<<b[t].x<<","<<b[t].y<<")";
	}else{
		s++; //记录步数
		ct(b[t].fa);
		cout<<"->"<<"("<<b[t].x<<","<<b[t].y<<")";
	}
}
void bfs(int x,int y){
	head=0;tail=1;
	b[1].fa=0;
	b[1].x=sx;b[1].y=sy;
	c[sx][sy]=1;
	//初始化
	do{
		head++;
		x=b[head].x;y=b[head].y;
		for(int i=0;i<=3;i++){
			int xx=x+fx[i][0],yy=y+fx[i][1];
			if(check(xx,yy)){
				tail++;
				c[xx][yy]=1;//c记录节点是否走过
				b[tail].fa=head;
				b[tail].x=xx;
				b[tail].y=yy;
				//b[i].fa表示节点i的父节点,b.x,b.y表示坐标位置
				if(xx==ex&&yy==ey){
					ct(tail); //递归回去输出路径
					cout<<endl<<s;
					return;
				}
			}
		}
	}while(head!=tail);
}
int main(){
	in();
	bfs(sx,sy);
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值