标签:
Description
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.
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.
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.
1 #include<iostream>
2 #include<queue>
3 #include<cstring>
4 #include<string>
5 using namespace std;
6 const int maxn=20+5;
7 int bad[maxn][maxn],p[maxn][maxn][maxn];
8 int go[4][2]={0,1,1,0,-1,0,0,-1};
9 int m,n,k;
10 int check(int x,int y)
11 {
12 if(x<0 || y<0 || x>=m || y>=n)
13 return 1;
14 return 0;
15 }
16 struct node
17 {
18 int x;
19 int y;
20 int t;
21 int d;
22 }temp,temp1,temp2;
23 int main()
24 {
25 int T,dx,dy,i,j;
26 cin>>T;
27 while(T--)
28 {
29 memset(p,0,sizeof(p));
30 cin>>m>>n>>k;
31 p[0][0][0]=1;
32 for(i=0;i<m;i++)
33 for(j=0;j<n;j++)
34 cin>>bad[i][j];
35 dx=m-1;
36 dy=n-1;
37 struct node temp={0,0,0,0};
38 queue<node>q;
39 q.push(temp);
40 while(!q.empty())
41 {
42 temp1=q.front();
43 q.pop();
44 if(temp1.x==dx&&temp1.y==dy)
45 {
46 cout<<temp1.t<<endl;
47 break;
48 }
49 for(i=0;i<4;i++)
50 {
51 temp2.x=temp1.x+go[i][0];
52 temp2.y=temp1.y+go[i][1];
53 temp2.t=temp1.t+1;
54 if(bad[temp2.x][temp2.y])
55 temp2.d=temp1.d+1;
56 else
57 temp2.d=0;
58 if(check(temp2.x,temp2.y))
59 continue;
60 if(p[temp2.x][temp2.y][temp2.d]==1)
61 continue;
62 if(temp2.d<=k)
63 {
64 p[temp2.x][temp2.y][temp2.d]=1;
65 q.push(temp2);
66 }
67
68
69 }
70 if(q.empty())
71 cout<<-1<<endl;
72 }
73 }
74 return 0;
75 }
标签:
原文地址:http://www.cnblogs.com/huaxiangdehenji/p/4674686.html