您的位置:首页 > 其它

nyoj 坦克大战 (优先队列)

2015-03-15 11:26 253 查看
BFS题目。输入完图之后可以先预处理一下,然后用优先队列解决。

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<string>
#include<queue>
#include<algorithm>
#include<map>
#include<iomanip>
#include<climits>
#include<string.h>
#include<cmath>
#include<stdlib.h>
#include<vector>
#include<set>
#define INF 1e7
#define MAXN 100010
#define maxn 111
#define maxm 1000
#define Mod 1000007
#define MIN(a,b) (a < b ? a : b)
#define MAX(a,b) (a > b ? a : b)
#define mem(a) memset(a,0,sizeof(a))
using namespace std;
typedef long long LL;
int n, m;
int sx, sy, fx, fy;
char G[333][333];
int mp[333][333];
int vis[333][333];
int dx[] = { 1, -1, 0, 0 }, dy[] = { 0, 0, 1, -1 };

struct node {
int x, y, step;
bool operator <(const node a) const {
return step > a.step;
}
};

bool check(int x, int y)
{
if (vis[x][y] || x < 0 || y < 0 || x >= n || y >= m)
return true;
return false;
}

int bfs()
{
priority_queue<node> q;
q.push({ sx, sy, 0 });
vis[sx][sy] = 1;
while (!q.empty()) {
node now = q.top();
q.pop();
if (now.x == fx && now.y == fy)
return now.step;
node next;
for (int i = 0; i < 4; ++i) {
next.x = now.x + dx[i];
next.y = now.y + dy[i];
next.step = now.step;
if (check(next.x, next.y)) continue;
if (mp[next.x][next.y] != -1) {
q.push({ next.x, next.y, next.step + mp[next.x][next.y] });
vis[next.x][next.y] = 1;
}
}
}
return -1;
}

int main()
{
while (~scanf("%d%d",&n,&m), n + m) {
memset(vis,0,sizeof(vis));
memset(mp,0,sizeof(mp));
for (int i = 0; i < n; ++i) {
scanf("%s", G[i]);
for (int j = 0; j < m; ++j) {
if (G[i][j] == 'Y')
sx = i, sy = j;
else if (G[i][j] == 'T')
fx = i, fy = j;
}
}
for (int i = 0; i < n; ++i)
for (int j = 0; j < m; ++j) {
if (G[i][j] == 'S' || G[i][j] == 'R') mp[i][j] = -1;
else if (G[i][j] == 'B') mp[i][j] = 2;
else if (G[i][j] == 'E' || G[i][j] == 'T') mp[i][j] = 1;
}
cout << bfs() << endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: