您的位置:首页 > 其它

Uva1600——Patrol Robot

2016-03-05 17:47 375 查看
这题:找最短路径,只是可以跨越障碍,不能连续跨越K个障碍。

可以通过BFS做。

一开始我没有用vis数组,是在输入的矩阵中操作的,结果一直WR,不明白,为毛加了vis就可以,同样是标记的,自己还是有待提高。

下面AC代码:

#include <iostream>
#include <queue>
#include <cstring>
using namespace std;

struct node
{
int x, y, count, sum;    //xy为坐标,count为走了多少步,sum为连续跨越几个障碍了。
};

int xy[4][2] = {{0, -1}, {1, 0}, {0, 1}, {-1, 0}};
int num[25][25];
int n, m, k;

bool vis[25][25][25];

int bfs(int x1, int y1, int x2, int y2)
{
node no;
no.x = x1; no.y = y1;
no.count = 0;
/*	if(num[x1][y1] == 1)    //起点是1,看作已经跨越障碍了,不需要障碍数 + 1.
no.sum = 1;
else*/
no.sum = 0;
queue<node> Q;
Q.push(no);
memset(vis, 0, sizeof(vis));
vis[0][0][0] = true;
//	num[x1][y1] = -1;
while(!Q.empty())
{
node nod = Q.front();
Q.pop();
if(nod.x == x2 && nod.y == y2)
return nod.count;

for(int i = 0; i < 4; i++)
{
int x = nod.x + xy[i][0], y = nod.y + xy[i][1], z = nod.count, s = nod.sum;
if(!(x >= 0 && x < n && y >= 0 && y < m))
continue;
if(num[x][y])
s++;
else
s = 0;
if(s > k || vis[x][y][s])
continue;
vis[x][y][s] = true;
no.x = x; no.y = y;
no.count = z + 1;
no.sum = s;
Q.push(no);
}
}
return -1;
}

int main()
{
freopen("1.txt", "r", stdin);
int t;
cin >> t;
while(t--)
{
cin >> n >> m;
cin >> k;
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++)
cin >> num[i][j];
int x1 = 0, y1 = 0, x2 = n - 1, y2 = m - 1;
cout << bfs(x1, y1, x2, y2) << endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: