#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
using namespace std;
const int maxn=30;
int t,n,m,k;
int Mao[maxn][maxn],vis[maxn][maxn][maxn];//三维数组第三维表示已经走过的障碍物的个数,值仍旧表示是否访问过
int dx[]= {0,0,0,-1,1},dy[]= {0,-1,1,0,0};
struct P
{
int x,y,step,obs;
} p,q;
int BFS()
{
queue<P> qu;
p.x=1;
p.y=1;
p.step=0;
if(Mao[1][1]==1) p.obs=1;
else p.obs=0;
qu.push(p);
while(!qu.empty())
{
q=qu.front();
//cout << q.x << ":" << q.y << endl;
qu.pop();
if(q.x==n && q.y==m) return q.step;
vis[q.x][q.y][q.obs]=1;
for(int i=1; i<=4; i++)
{
int nx=q.x+dx[i];
int ny=q.y+dy[i];
if(nx<=n && ny<=m && nx>=1 && ny>=1)//先判断坐标是否合法
{
p.x=nx;
p.y=ny;
if(Mao[nx][ny]==1)//如果下一个位置是障碍物
{
if(q.obs<k && !vis[nx][ny][q.obs+1])//如果没访问过且还没到达k个障碍物
{
p.step=q.step+1;
p.obs=q.obs+1;
qu.push(p);
}
}
else//如果下一个位置是空地
{
if(!vis[nx][ny][0])//如果没访问过
{
p.step=q.step+1;
p.obs=0;
qu.push(p);
}
}
}
}
}
return -1;
}
int main()
{
scanf("%d",&t);
while(t--)
{
memset(vis,0,sizeof(vis));
memset(Mao,0,sizeof(Mao));
scanf("%d%d%d",&n,&m,&k);
for(int i=1; i<=n; i++)
for(int j=1; j<=m; j++)
scanf("%d",&Mao[i][j]);
int ans=BFS();
printf("%d\n",ans);
}
return 0;
}
现在看来和bfs板子完全一样,只是标记访问的vis变了而已,然后中间讨论一下下一个位置的情况