您的位置:首页 > 其它

nyoj--284 坦克大战(bfs+优先队列)

2016-03-19 12:36 471 查看
nyoj 284

题解

与一般的迷宫问题不同,这里的每一点如果可扩展,可能要走1步或者2步,如果用普通的队列,无法保证到达终点时步数最少。

因此使用优先队列,每一次走都选择步数最少的进行扩展。

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

const int maxn = 300 + 10;
const int inf  = 1 << 30;
char  maze[maxn][maxn];
int   dir[4][2] = { {-1, 0}, {1, 0}, {0, 1}, {0, -1} };
int   sx, sy, ex, ey;
int   m, n;

struct node{
int x, y;
int turn;
bool operator < (const node& rhs) const { return turn > rhs.turn; }
};

int bfs()
{
priority_queue<node> Q;
Q.push(node{sx, sy, 0});
while(!Q.empty())
{
node u = Q.top();
Q.pop();
if(u.x == ex && u.y == ey) return u.turn;
for(int i = 0; i < 4; ++i)
{
int nx = u.x + dir[i][0], ny = u.y + dir[i][1];
if(nx < 0 || nx >= m || ny < 0 || ny >= n || maze[nx][ny] == 'S' || maze[nx][ny] == 'R')
continue;
if(maze[nx][ny] == 'B') Q.push(node{nx, ny, u.turn + 2});
else Q.push(node{nx, ny, u.turn + 1});
maze[nx][ny] = 'S'; //访问过的不再访问,防止扩展
}
}
return -1;
}

int main()
{
while(cin >> m >> n && (m || n))
{
for(int i = 0; i < m; ++i)
{
for(int j = 0; j < n; ++j)
{
cin >> maze[i][j];
if(maze[i][j] == 'Y') sx = i, sy = j;
if(maze[i][j] == 'T') ex = i, ey = j;
}
}
cout << bfs() << endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  nyoj bfs easy++