您的位置:首页 > 其它

算法竞赛入门经典 第二版 习题6-5 巡逻机器人 Patrol Robot uva1600

2017-04-18 20:43 411 查看
题目:https://vjudge.net/problem/UVA-1600

思路:BFS求最短路径问题,需要注意对于穿过障碍时的处理,具体见代码及注释。

代码:C++

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

const int movex[] = {0, 0, -1, 1};
const int movey[] = {-1, 1, 0, 0};
int m, n, k;//行数、列数、最多穿过连续障碍数

struct cell
{
int first, second;//行、列
int consistk;//到达此处连续穿过的障碍数
bool obstacle;//表征此处是否为障碍
bool reach;//是否被访问
int step;//步数
cell() {}
cell(int fir, int sec, int obs)
: first(fir), second(sec), obstacle(obs), step(0), consistk(0), reach(false) {}
};

cell pic[30][30];

int bfs()
{
queue<cell *> q;
pic[1][1].reach = true;
if(pic[1][1].obstacle)
{
pic[1][1].consistk++;
}
q.push(&pic[1][1]);
while(!q.empty())
{
cell *t = q.front();
q.pop();
int row = t->first, column = t->second;
if(row==m&&column==n)
{
return t->step;
}
for(int i=0; i<4; i++)
{
int r = row+movex[i];
int c = column+movey[i];
if(r>=1&&r<=m&&c>=1&&c<=n)
{
//未被访问过或同步数时穿过的障碍数少时可以走
if(!pic[r][c].reach||(t->step+1==pic[r][c].step&&t->consistk<pic[r][c].consistk))
{
if(pic[r][c].obstacle)
{
if(t->consistk==k)
{
continue;
}
else
{
pic[r][c].consistk = t->consistk+1;
}
}
pic[r][c].step = t->step+1;
pic[r][c].reach = true;
q.push(&pic[r][c]);
}
}
}
}
return -1;
}

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