您的位置:首页 > 产品设计 > UI/UE

1012 Rescue

2016-04-18 22:55 381 查看
题意:

X代表卫兵,a代表终点,r代表起始点,.代表路,#代表墙路花费一秒,x花费两秒问到达终点的最少时间

思路:

BFS 问题 很普通的一个问题 用优先队列解决

求出所有的情况 重载运算符‘<’将所有情况放于优先队列中 输出最小的

// ConsoleApplication17.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<fstream>
#include<iostream>
#include <stdio.h>
#include <string.h>
#include <queue>
using namespace std;
struct node
{
int x, y, step;
friend bool operator<(node n1, node n2)
{
return n2.step<n1.step;
}
};
int n, m, visit[205][205];
char map[205][205];
int sx, x2, sy, y2;
int to[4][2] = { 1,0,-1,0,0,1,0,-1 };
int check(int x, int y)
{
if (x<0 || y<0 || x >= n || y >= m || !visit[x][y] || map[x][y] == '#')
return 1;
return 0;
}
int bfs()
{
int i;
priority_queue<node> Q;
node a, next;
a.x = sx;
a.y = sy;
a.step = 0;
Q.push(a);
visit[sx][sy] = 0;
while (!Q.empty())
{
a = Q.top();
Q.pop();
if (a.x == x2 && a.y == y2)
return a.step;
for (i = 0; i<4; i++)
{
next = a;
next.x += to[i][0];
next.y += to[i][1];
if (check(next.x, next.y))
continue;
next.step++;
if (map[next.x][next.y] == 'x')
next.step++;
if (visit[next.x][next.y] >= next.step)
{
visit[next.x][next.y] = next.step;
Q.push(next);
}
}
}
return 0;
}
int main()
{
fstream cin("E:/C++/IN/aaa.txt");
int i, j;
while (cin>>n>>m)
{
for (i = 0; i < n; i++)
for (j = 0;j < m;j++)
cin >> map[i][j];
for (int i = 0;i < n;i++)
for (j = 0; map[i][j]; j++)
{
if (map[i][j] == 'r')
{
sx = i;
sy = j;
}
else if (map[i][j] == 'a')
{
x2 = i;
y2 = j;
}
}
}
memset(visit, 1, sizeof(visit));
int ans = 0;
ans = bfs();
if (ans)
cout<<ans<<endl;
else
cout << "Poor ANGEL has to stay in the prison all his life." << endl;;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: