原题链接:https://vjudge.net/problem/UVA-1600
分类:图
备注:水题
代码如下:
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
const int dir[4][2] = { {-1,0},{1,0},{0,-1},{0,1} };
int T, m, n, k, vised[25][25][25], a[25][25];
struct node {
int row, col, sum, step;
node(int x, int y, int n, int t) :
row(x), col(y), sum(n), step(t) {}
};
bool check(int row, int col) {
if (row<1 || row>m || col<1 || col>n)return false;
return true;
}
int main(void) {
scanf("%d", &T);
while (T--) {
memset(vised, 0, sizeof(vised));
scanf("%d %d %d", &m, &n, &k);
for (int i = 1; i <= m; i++)
for (int j = 1; j <= n; j++)
scanf("%d", &a[i][j]);
node head(1, 1, 0, 0);
queue<node>q;
q.push(head);
int ok = 0, sum;
while (!q.empty()) {
head = q.front(); q.pop();
if (head.row == m && head.col == n) {
ok = 1; break;
}
for (int i = 0; i < 4; i++) {
int row = head.row + dir[i][0];
int col = head.col + dir[i][1];
if (!check(row, col))continue;
if (!a[row][col])sum = 0;
else if ((sum = head.sum+1) > k)continue;
if (vised[row][col][sum])continue;
int step = head.step + 1;
vised[row][col][sum] = 1;
q.push(node(row, col, sum, step));
}
}
if (ok)printf("%d\n", head.step);
else printf("-1\n");
}
return 0;
}