机器人走迷宫(uva 1600)
来源:互联网 发布:log4j源码分析 编辑:程序博客网 时间:2024/04/29 09:38
A robot has to patrol around a rectangulararea which is in a form of m × n grid (m rows and n columns). The rows arelabeled from 1 to m. The columns are labeled from 1 to n. A cell (i, j) denotesthe cell in row i and column j in the grid. At each step, the robot can onlymove from one cell to an adjacent cell, i.e. from (x, y) to (x + 1, y), (x, y +1), (x − 1, y) or (x, y − 1). Someof the cells in the grid contain obstacles. In order to move to a cellcontaining obstacle, the robot has to switch to turbo mode. Therefore, therobot cannot move continuously to more than k cells containing obstacles. Yourtask is to write a program to find the shortest path (with the minimum numberof cells) from cell (1, 1) to cell (m, n). It is assumed that both these cellsdo not contain obstacles.
Input
The input consists of several data sets.The first line of the input file contains the number of data sets which is apositive integer and is not bigger than 20. The following lines describe thedata sets. For each data set, the first line contains two positive integernumbers m and n separated by space (1 ≤ m, n ≤ 20). The second line contains aninteger number k (0 ≤ k ≤ 20). The i-th line of the next m lines contains ninteger aij separated by space (i = 1, 2, . . . , m; j = 1, 2, . . . , n). Thevalue of aij is ‘1’ if there is an obstacle on the cell (i, j), and is ‘0’otherwise.
Output For each data set, if there exists away for the robot to reach the cell (m, n), write in one line the integernumber s, which is the number of moves the robot has to make; ‘-1’ otherwise.
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个。因为dfs是广度优先,所以第一次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;}