Uva 1600 - Patrol Robot (BFS)

题目链接 https://vjudge.net/problem/UVA-1600


Sample Input

3

2 5

0

0 1 0 0 0

0 0 0 1 0

4 6

1

0 1 1 0 0 0

0 0 1 0 1 1

0 1 1 1 1 0

0 1 1 1 0 0

2 2

0

0 1

1 0

 

Sample Output

7

10

-1

 

【题意】

机器人走迷宫,求最短路径,0是空地,1是障碍物,机器人最多可以连续走k个障碍物。

 

【思路】

   对最基础的bfs求最短路的方法稍作拓展,对访问标记数组增加一个状态,used[k][r][c]表示到达(r,c)位置时连续穿过的障碍物个数为k个。因为bfs是广度优先,所以第一次used[k][r][c]==true时对应的距离也是最短的,所以用同样的方法即可求出符合要求的最短路。

#include<bits/stdc++.h>
using namespace std;

const int maxn = 50;
const int dx[] = { 0, 1, 0, -1 };
const int dy[] = { 1, 0, -1, 0 };

int m, n, k;
int mp[maxn][maxn];
bool used[maxn][maxn][maxn];

struct node {
	int r, c, move, num;//行,列,当前路径长度,当前连续穿过的障碍物数目 
	node(int rr = 0, int cc = 0, int m = 0, int n = 0):r(rr),c(cc),move(m),num(n) {}
};

void bfs() {
	memset(used, false, sizeof used);
	queue<node> que;
	que.push(node(1,1,0,0));
	
	while (!que.empty()) {
		node tmp = que.front();
		que.pop();
		
		for (int d = 0; d < 4; ++d) {
			int r = tmp.r + dx[d];
			int c = tmp.c + dy[d];
			
			if (r >= 1 && r <= m && c >= 1 && c <= n) {
		
				int move = tmp.move + 1;
				int num = mp[r][c] ? 1 + tmp.num : 0;
					
				if (!used[num][r][c] && num <= k) {
					if (r == m && n == c) {
						printf("%d\n", move);
						return;
					}
					que.push(node(r, c, move, num));
					used[num][r][c] = true;
				}
			}
		}
	}
	printf("-1\n");
}

int main() {
	int t;
	scanf("%d", &t);
	while (t--) {
		scanf("%d%d%d", &m, &n, &k);
		for (int i = 1; i <= m; ++i) {
			for (int j = 1; j <= n; ++j) scanf("%d", &mp[i][j]);
		}
		bfs();
	}
	return 0;
}


posted @ 2017-12-25 16:46  不想吃WA的咸鱼  阅读(94)  评论(0编辑  收藏  举报