紫书UVA1600
这个题的第二组数据一直过不了,原因是int layer=t.layer写在了for的外面,导致每一个方向共用了一个layer。
/*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
(1 ≤ m, n ≤ 20). The second line contains an integer number k (0 ≤ k ≤ 20). The i-th 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*/
#include <bits/stdc++.h>
using namespace std;
int a[25][25],vis[25][25][25];
int dx[]={1,0,-1,0};
int dy[]={0,1,0,-1};
int m,n,k;
struct node
{
int x,y,layer,step;
node(int x=1,int y=1,int l=0,int s=0):x(x),y(y),layer(l),step(s){}
};
int cas=0;
int bfs()
{
queue <node> q;
memset(vis,0,sizeof(vis));
q.push(node(1,1,0,0));
// vis[1][1][0]=1;
while(!q.empty())
{
node t=q.front();
int x=t.x;
int y=t.y;
int step=t.step;
q.pop();
if(x==m&&y==n)
return step;
// cout<<t.step<<endl;
for(int i=0;i<4;i++)
{
int x1=x+dx[i];
int y1=y+dy[i];
int layer=t.layer;//此处没写对位置导致我第二组数据答案出错
if(a[x1][y1])
layer++;
else
layer=0;
if(x1>0&&x1<=m&&y1>0&&y1<=n&&!vis[x1][y1][layer]&&layer<=k)
{
vis[x1][y1][layer]=1;
q.push(node(x1,y1,layer,step+1));
}
}
}
return -1;
}
int main()
{
int t;
cin>>t;
while(t--)
{
cin>>m>>n>>k;
for(int i=1;i<=m;i++)
{
for(int j=1;j<=n;j++)
{
cin>>a[i][j];
}
}
cout<<bfs()<<endl;
}
return 0;
}