描述
A robot has to patrol around a rectangular area which is in a form of mxn grid (m rows and n columns). The rows are labeled from 1 to m. The columns are labeled from 1 to n. A cell (i, j) denotes the cell in row i and column j in the grid. At each step, the robot can only move 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). Some of the cells in the grid contain obstacles. In order to move to a cell containing obstacle, the robot has to switch to turbo mode. Therefore, the robot cannot move continuously to more than k cells containing obstacles.
Your task is to write a program to find the shortest path (with the minimum number of cells) from cell (1, 1) to cell (m, n). It is assumed that both these cells do 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 a positive integer and is not bigger than 20. The following lines describe the data sets.
For each data set, the first line contains two positive integer numbers m and n separated by space (1m, n20). The second line contains an integer number k(0k20). The ith line of the next m lines contains n integer aij separated by space (i = 1, 2,..., m;j = 1, 2,..., n). The value 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 a way for the robot to reach the cell (m, n), write in one line the integer number 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
***解题思路:
用一个vis[x][y][z]表示走到x,y的时候 穿过了z个墙,标记现在的步数
进行递归的条件是,走到下一步时候,之前走到这里的步数必须下与之后走到这里的步数。
程序代码:
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
#include <queue>
#define maxn 20+5
using namespace std;
int map[maxn][maxn],vis[maxn][maxn][maxn];
int m,n,k,ans;
int dx[]={,,,-};
int dy[]={,-,,};
struct Node{
int x,y;
int cnt;
int k;
}; int bfs(){
queue<Node> q;
Node u;
u.x=;u.y=;u.cnt=;u.k=k;
vis[][][k]=;
q.push(u);
while (!q.empty()){
u=q.front();q.pop();
if (u.x==n-&&u.y==m-){
ans=u.cnt;
return ;
}
Node v;
if (u.k>=)//如果到该点没有命了, 那么就不需要在该点扩展了
for (int i=;i<;i++){
v.x=u.x+dx[i];
v.y=u.y+dy[i];
v.cnt=u.cnt+;
if (map[v.x][v.y]) v.k=u.k-;
else v.k=k;//碰到0就恢复满命
if (v.x>=&&v.x<n&&v.y>=&&v.y<m&&!vis[v.x][v.y][v.k]){
if (v.k>=) {q.push(v);vis[v.x][v.y][v.k]=;}
}
}
}
if (q.empty()) ans=-;
}
int main()
{
int T;
cin>>T;
while (T--){
memset(map,,sizeof(map));
memset(vis,,sizeof(vis));
cin>>n>>m>>k;
for (int i=;i<n;i++)
for (int j=;j<m;j++)
cin>>map[i][j];
bfs();
cout<<ans<<endl;
}
}