迷宫最短路径

Description

为了测试某种药物对小白鼠方向感的影响,生物学家在实验室做了一个矩形迷宫,入口和出口都确定为唯一的,且分布在矩形的不同边上。现在让你算出小白鼠最短需要走多少步,才可以从入口走到出口。

Input

N+1行,第一行为NN=0表示输入结束),以下NN0-1矩阵,1表示不能通过0表示可以通过左上角和右下角为0,即入口和出口),其中N<30

Output

只有一个数,为最少要走的格子数。0表示没有路径。

Sample Input
 Copy sample input to clipboard
5
0 1 1 1 1
0 0 1 1 1
1 0 0 0 1
1 1 1 0 1
1 1 1 0 0
4
0 0 1 1
0 0 0 1
1 1 1 1
1 1 1 0
0
Sample Output
9
0
#include <iostream>
#include <queue>


using namespace std;


int arr[4][2] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};		//定义四个方向


struct Node {
	int x;
	int y;
	int step;
	Node(int x1, int y1, int step1) : x(x1), y(y1), step(step1) { }
};


int BFS(int n, int *maze) {
	int *p = new int[n*n]; 
	for (int i = 0; i < n*n; ++i) p[i]= 0; //如果没有经过则为0,经过则为1
	
	queue<Node> q;
	Node node(0, 0, 1);
	q.push(node);
	while (!q.empty()) {
		node = q.front();
		q.pop();
		
		//上下左右都走一遍
		if (node.x == n-1 && node.y == n-1) { delete p; return  node.step;}
		p[node.x*n+node.y] = 1;
		for (int i = 0; i < 4; ++i) {
			int x = node.x + arr[i][0];                  
			int y = node.y + arr[i][1];
			
	if (x >= 0 && y >= 0 && x < n && y < n && p[x*n+y] == 0 && maze[x*n+y] == 0) {
		p[x*n+y] = 1;
		Node next(x, y, node.step + 1);
		q.push(next);
	}
	}
	}
	delete p;


	return -1;
}


int main()
{
	int n;


	int all_step;


	while (cin >> n) {
		if (n == 0) { return 0;}
	int *maze = new int[n*n];
	for (int i = 0; i < n*n; ++i ) {
		cin >> maze[i];
	}
	if (n == 1 && maze[0] == 1) {
		cout << 0 << endl;
		return 0;
	}
	all_step = 0;
	all_step = BFS(n, maze);
	if (all_step == -1) {
		cout << "0" << endl;
	} else cout << all_step << endl;


		delete maze;
		system ("pause");
	}


	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值