描述
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[]={0,0,1,-1}; int dy[]={1,-1,0,0}; struct Node{ int x,y; int cnt; int k; }; int bfs(){ queue<Node> q; Node u; u.x=0;u.y=0;u.cnt=0;u.k=k; vis[0][0][k]=1; q.push(u); while (!q.empty()){ u=q.front();q.pop(); if (u.x==n-1&&u.y==m-1){ ans=u.cnt; return 0; } Node v; if (u.k>=0)//如果到该点没有命了, 那么就不需要在该点扩展了 for (int i=0;i<4;i++){ v.x=u.x+dx[i]; v.y=u.y+dy[i]; v.cnt=u.cnt+1; if (map[v.x][v.y]) v.k=u.k-1; else v.k=k;//碰到0就恢复满命 if (v.x>=0&&v.x<n&&v.y>=0&&v.y<m&&!vis[v.x][v.y][v.k]){ if (v.k>=0) {q.push(v);vis[v.x][v.y][v.k]=1;} } } } if (q.empty()) ans=-1; } int main() { int T; cin>>T; while (T--){ memset(map,0,sizeof(map)); memset(vis,0,sizeof(vis)); cin>>n>>m>>k; for (int i=0;i<n;i++) for (int j=0;j<m;j++) cin>>map[i][j]; bfs(); cout<<ans<<endl; } }