用一个三维数组,数组的前面两项下标表示的是数组中元素的位置,后一项下标表示的是对应的已经穿越了连续的障碍的个数,然后BFS,每次判断相应的待探测下一个点是否满足如下条件:第一,是否能够满足连续障碍数小于等于k;第二,下一个点是否没有探测过;第三,如果下一个点已经探测过了,那么当前的走法所走的路程长度是否小于已经探测得到的长度。具体的实现见如下代码,注意,题目中的k不是指总的障碍数,而是指连续穿越的障碍数的总个数。
#include<iostream>
#include<vector>
#include<string>
#include<set>
#include<stack>
#include<queue>
#include<map>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include<cstring>
#include<sstream>
#include<cstdio>
using namespace std;
int length[25][25][25];
int area[25][25];
int Case, m, n,k;
int dir[4][2] = { 1, 0, -1, 0, 0, 1, 0, -1 };
void bfs(int x,int y,int k0,int cur){
length[x][y][k0] = cur;
if (x == m&&y == n) return;
for (int i = 0; i < 4; i++){
int newx = x + dir[i][0];
int newy = y + dir[i][1];
if (newx >= 1 && newx <= m&&newy >= 1 && newy <= n){
int newk;
if (area[newx][newy]) newk = k0 + 1;
else newk = 0;
if (newk <= k && (length[newx][newy][newk] == -1 || length[newx][newy][newk]>cur + 1))
bfs(newx, newy, newk, cur + 1);
}
}
}
int main(){
cin >> Case;
while (Case--){
cin >> m >> n >> k;
for (int i = 1; i <= m; i++){
for (int j = 1; j <= n; j++)
cin >> area[i][j];
}
memset(length,-1,sizeof(length));
bfs(1,1,0,0);
int mi = 10000000;
for (int i = 0; i <= k; i++){
if (length[m][n][i]>=0) mi = min(mi, length[m][n][i]);
}
if (mi == 10000000) cout << "-1" << endl;
else cout << mi<<endl;
}
return 0;
}