bfs hrbust 2074

逃生
Time Limit: 1000 MSMemory Limit: 65536 K
Total Submit: 132(55 users)Total Accepted: 53(43 users)Rating: Special Judge: No
Description

A淪落到了一個迷宮之中,這個迷宮由n*m個格子構成,有些格子是不能通過的,現在他要從迷宮入口(1,1)的格子走到迷宮出口(n,m)的格子。

因爲小A的方向感很弱,轉多了會暈,所以他走到目的地的時候,最多能轉z次,否則他就永遠暈倒在原地了,到了出口也沒法出去了。

請你告訴他最少能經過多少個格子走出迷宮。

Y(1,1)出發到達的第一個點都可以認爲不用轉向。

Input

有多組測試數據。

對於每組測試數據,第一行爲3個整數n, mz,表示n*m的迷宮,最多能轉z次。

接下來是n*m的字符矩陣,僅由01表示,0表示可以通過,1表示不可以通過。

2<=n,m<=100 1<=z<=50

Output

對於每組測試數據,輸出一行,包含一個整數,爲經過的最少格子數。如果無法到達目的地,輸出-1

Sample Input
2 3 3
011
000
3 2 3
01
11
00
5 5 3
00000
00000
00101
01000
00000
Sample Output
4
-1
9

AC代碼

#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
int n,m,k;
char str[105][105];
int map[105][105];
struct node{
	int x,y;
	int step;
	int turn;
};node u,v;
int tx[4] = {0,0,1,-1};
int ty[4] = {1,-1,0,0};
int judge(int x, int y)
{
	if (x >= n || x < 0 || y < 0 || y >= m || map[x][y] == 1)
		return 0;
	return 1;
}
int bfs (int x, int y){
	queue<node>s;
	u.x = x;
	u.y = y;
	u.step = 0;
	u.turn = -1;
	s.push(u);
	while(!s.empty())
	{
		u = s.front();
		s.pop();
//		if(u.x == n-1 && u.y == m-1 && u.turn <= k)
//			return u.step;
//		for(int i = 0; i < 4; i++)
//		{
//			v = u;
//			v.turn = u.turn + 1;
//			if(v.turn > k) continue;
//			v.x += tx[i];
//			v.y += ty[i];
//			v.step += 1;
//			while(judge(v.x,v.y))
//			{
//				s.push(v);
//				map[v.x][v.y] = 1;
//				v.x += tx[i];
//				v.y += ty[i];
//				v.step += 1;
//			}
//		}
		for(int i =0 ;i < 4; i++)
		{
			v = u;
			v.turn = u.turn +1;
			v.x = v.x + tx[i];
			v.y = v.y + ty[i];
			v.step +=1;
			while(judge(v.x,v.y))
			{
				map[v.x][v.y] = 1;
				if(v.turn+1 <= k && v.x == n-1 && v.y == m-1)
					return v.step+1;
				s.push(v);
				v.x = v.x + tx[i];
				v.y = v.y + ty[i];
				v.step +=1;
			}
		}
	}
	return -1;
}
int main()
{
	while (~ scanf("%d%d%d",&n,&m,&k))
	{
		for (int i = 0; i < n; i++)
		{
			scanf("%s",str[i]);
		}
		for(int i = 0; i < n; i++)
			for(int j = 0; j < m; j++)
			{
				map[i][j] = str[i][j] - '0';
			}
		int ans = bfs(0,0);
		printf("%d\n",ans);
		
		
	}
	
}

發佈了46 篇原創文章 · 獲贊 6 · 訪問量 5438
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章