逃生
Time Limit: 1000 MS Memory Limit: 65536 K
Total Submit: 132(55 users) Total Accepted: 53(43 users) Rating: ![](http://acm.hrbust.edu.cn/Public/images/star-solid.png)
![](http://acm.hrbust.edu.cn/Public/images/star-solid.png)
![](http://acm.hrbust.edu.cn/Public/images/star-solid.png)
![](http://acm.hrbust.edu.cn/Public/images/star-half2.png)
Special Judge: No
Description 小A沦落到了一个迷宫之中,这个迷宫由n*m个格子构成,有些格子是不能通过的,现在他要从迷宫入口(1,1)的格子走到迷宫出口(n,m)的格子。
因为小A的方向感很弱,转多了会晕,所以他走到目的地的时候,最多能转z次,否则他就永远晕倒在原地了,到了出口也没法出去了。
请你告诉他最少能经过多少个格子走出迷宫。
小Y从(1,1)出发到达的第一个点都可以认为不用转向。
Input 有多组测试数据。
对于每组测试数据,第一行为3个整数n, m和z,表示n*m的迷宫,最多能转z次。
接下来是n*m的字符矩阵,仅由0和1表示,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);
}
}
bfs hrbust 2074
最新推荐文章于 2019-05-09 21:57:23 发布