您的位置:首页 > 其它

2016.6.22

2016-06-22 16:29 288 查看
1.拯救行动

题目链接:http://noi.openjudge.cn/ch0205/4980/

对广搜又有了新的认识。

这道题用到了优先级队列,并在struct里重载了<.这样就保证每次pop出来的是当前队列里时间最少的。

废话不多说,贴代码。

#include <iostream>
#include <cstring>
#include <queue>

using namespace std;

int m, n, ex, ey;
char map[202][202];
bool visited[202][202];
int dx[4] = { 0, 1, 0, -1 };
int dy[4] = { 1, 0, -1, 0 };
struct point
{
int x, y, t;
point(int x, int y, int t) :x(x), y(y), t(t){}
bool operator <(const point & a)const//注意重载要加const,否则报错
{
return a.t < t;
}

};
int main()
{
int s;
cin >> s;
while (s--)
{
cin >> n >> m;
priority_queue<point> q;
for (int i = 0; i < n; ++i)
for (int j = 0; j < m; ++j)
{
visited[i][j] = false;
cin >> map[i][j];
if (map[i][j] == 'r')
{
q.push(point(i, j, 0));
map[i][j] = '@';
visited[i][j] = true;
}
if (map[i][j] == 'a')
{
ex = i;
ey = j;
}
}
int flag = 1;
while (!q.empty())
{
point temp = q.top();
q.pop();
if (temp.x == ex && temp.y == ey)
{
flag = 0;
cout << temp.t << endl;
break;
}
for (int i = 0; i < 4; ++i)
{
int xx = temp.x + dx[i];
int yy = temp.y + dy[i];
if (xx >= 0 && xx < n && yy >= 0 && yy < m && !visited[xx][yy] && map[xx][yy] != '#')
{
if (map[xx][yy] == 'x')
{
q.push(point(xx, yy, temp.t + 2));
visited[xx][yy] = true;
}
else
{
q.push(point(xx, yy, temp.t + 1));
visited[xx][yy] = true;
}
}
}
}
if (flag)
cout << "Impossible" << endl;
}
return 0;
}

2.迷宫问题

题目链接:http://noi.openjudge.cn/ch0205/7084/

这道广搜题比较不同的地方在他要把最短路径给输出出来,这样queue就无法满足要求,因为每个用完的q就会被pop出去。

所以此题需要用struct数组来代替队列,并增加一个量pre,来存当前元素之前的元素位置。

直接通过代码体会。

#include&
4000
lt;iostream>
using namespace std;
int map[5][5];
int dx[4] = { 1, -1, 0, 0 };
int dy[4] = { 0, 0, -1, 1 };
int front = 0, rear = 1;
struct node
{
int x, y, pre;
}q[100];

void print(int i)
{
if (q[i].pre != -1)
{
print(q[i].pre);
cout << "(" << q[i].x << ", " << q[i].y << ")" << endl;
}
}
void bfs(int x1, int y1)
{
q[front].x = x1;
q[front].y = y1;
q[front].pre = -1;
while (front < rear)
{
if (q[front].x == 4 && q[front].y == 4)
{
print(front);
break;
}
for (int i = 0; i < 4; ++i)
{
int xx = q[front].x + dx[i];
int yy = q[front].y + dy[i];
if (xx >= 0 && xx < 5 && yy >= 0 && yy < 5 && !map[xx][yy])
{
map[xx][yy] = 1;
q[rear].x = xx;
q[rear].y = yy;
q[rear].pre = front;
rear++;
}
}
front++;
}
}

int main()
{
for (int i = 0; i < 5; ++i)
for (int j = 0; j < 5; ++j)
cin >> map[i][j];
cout << "(0, 0)" << endl;
bfs(0, 0);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: