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

ZOJ 1649 广度优先搜索与ACM的一道典型搜索题(使用GUI程序模拟搜索过程)

2008-07-02 20:36 609 查看
程序代码:

#include <iostream>
#include <queue>
#include <fstream>
#include <iomanip>
using namespace std;

struct Point
{
int x, y;
void operator=(Point pt) { x = pt.x, y = pt.y; }
bool operator==(Point pt) { return x == pt.x && y == pt.y; }
Point operator+(Point pt)
{
Point Tmp;
Tmp.x = x + pt.x;
Tmp.y = y + pt.y;
return Tmp;
}
};

char Map[201][201];
int Dist[201][201] = {0};
int row, col;

inline bool IsValid(Point pt)
{
if (pt.x >= 0 && pt.x < row && pt.y < col && pt.y >= 0)
if (Map[pt.x][pt.y] != '#' && Dist[pt.x][pt.y] == 0)
return true;
return false;
}

void Find(Point& start, Point& angel)
{
int cnt = 0;
for (int i = 0; i != row && cnt != 2; ++i)
{
for (int j = 0; j != col && cnt != 2; ++j)
{
if (Map[i][j] == 'r')
{
start.x = i;
start.y = j;
++cnt;
}
else if (Map[i][j] == 'a')
{
angel.x = i;
angel.y = j;
++cnt;
}
}
}
}

void BFS(Point start, Point angel)
{
queue<Point> Queue;
const Point xy[4] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};

++Dist[start.x][start.y];
Queue.push(start);
while (!Queue.empty())
{
Point pt = Queue.front();
Queue.pop();
if (Map[pt.x][pt.y] == 'x')
{
Map[pt.x][pt.y] = '.';
++Dist[pt.x][pt.y];
Queue.push(pt);
}
else
{
for (int i = 0; i != 4; i++)
{
Point newpt = pt + xy[i];
if (IsValid(newpt))
{
Dist[newpt.x][newpt.y] = Dist[pt.x][pt.y] + 1;
if (newpt == angel)
return;
Queue.push(newpt);
}
}
}
}
}

int main()
{
//ifstream cin("data.txt");
while (cin >> row >> col)
{
for (int i = 0; i != row; i++)
cin >> Map[i];

memset(Dist, 0, sizeof(Dist));

Point start = {-1, -1}, angel = {-1, -1};
Find(start, angel);
BFS(angel, start);
if (Dist[start.x][start.y] == 0)
cout << "Poor ANGEL has to stay in the prison all his life." << endl;
else
cout << Dist[start.x][start.y] - 1 << endl;
}

return 0;
}

算法效果模拟:

1、模拟程序界面:模拟程序初始画面根据如下的题目自带的测试数据生成。

7 8
#.#####.
#.a#..r.
#..#x...
..#..#.#
#...##..
.#......
........



2、广度优先搜索的结果:从结果可见,广度优先搜索不但能找到一条路径,而且还能保证是最短的。因为每个方向都探测过,并把所走的步数记录了下来。这样最少的步数就是最短的路径。



3、深度优先搜索的结果:从结果可见,深度优先搜索能够找到一条路径,但是不能保证是最短的。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: