#include<iostream>
#include<string>
#include<queue>
#include<cstring>
using namespace std;
struct point
{
int x;
int y;
point(const int x=-1,const int y=-1):x(x),y(y){}
};
struct status
{
point pos;
int turbo;
status(const point&p,const int o=0):pos(p),turbo(o){}
};
point operator+(const point& A,const point&B)
{
return point(A.x + B.x, A.y + B.y);
}
bool operator==(const point& A, const point& B)
{
return A.x == B.x && A.y == B.y;
}
const int maxn = 20 + 2;
int m, n;
int k;
point dir[4] = { {0,1},{0,-1},{1,0},{-1,0} };
int vis[maxn][maxn];
int ob[maxn][maxn];
const int inf = 10000;
int grid[maxn][maxn];
bool isvalid(point start, point direct)
{
if (start.x + direct.x >= m || start.x + direct.x < 0
|| start.y + direct.y>=n || start.y + direct.y < 0)
return false;
return true;
}
int solve(const point &start,const point&final)
{
memset(vis, inf, sizeof(vis));
memset(ob, inf, sizeof(ob));
queue<status>q;
q.push(status(start,0));
vis[0][0] = 0;
ob[0][0] = 0;
while (!q.empty())
{
status cur = q.front();
q.pop();
if (cur.pos == final)
{
return vis[final.x][final.y];
}
for (int i = 0; i < 4; ++i)
{
point mdir = dir[i];
if (isvalid(cur.pos, mdir))
{
point jump = cur.pos + mdir;
int curobs = cur.turbo;
if (grid[jump.x][jump.y] == 1)
++curobs;
else
curobs = 0;
if (curobs > k)
continue;
if (vis[jump.x][jump.y] > vis[cur.pos.x][cur.pos.y] + 1||curobs<ob[jump.x][jump.y])
{
vis[jump.x][jump.y] = vis[cur.pos.x][cur.pos.y] + 1;
ob[jump.x][jump.y] = curobs;
q.push(status(jump,curobs));
}
}
}
}
return -1;
}
int main()
{
int t;
cin >> t;
while (t-- > 0)
{
memset(grid, 0, sizeof(grid));
cin >> m >> n;
cin >> k;
for (int i = 0; i < m; ++i)
{
for (int j = 0; j < n; ++j)
cin >> grid[i][j];
}
cout << solve(point(0, 0), point(m - 1, n - 1)) << endl;
}
}
紫书UVa1600
最新推荐文章于 2024-09-23 14:27:27 发布