您的位置:首页 > 其它

2016.6.20

2016-06-20 20:55 281 查看
进入考试周...终于要开始复习程设了

先重新熟练一下bfs,找了道经典的题目:

红与黑(题目链接:http://noi.openjudge.cn/ch0205/1818/

总结一下bfs基本题型的做题要素:

1.使用队列,大部分情况下可以无脑写出来)

2.别忘了visited数组,记录哪些地方到过

3.dx[4],dy[4]数组,4次循环。

4.要设一个结构体,存点的坐标,在做找最短路径时还要记录走的步数。

贴代码

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

struct point
{
int x, y;
point(int x, int y) :x(x), y(y){}
};
int w, h;
int ans;
char map[25][25];
bool reach[25][25] = { false };
int dx[4] = { 0, 1, 0, -1 };
int dy[4] = { 1, 0, -1, 0 };
int main()
{
while (cin >> w >> h)
{
if (w == 0 && h == 0)
break;
queue<point> q;
ans = 0;
for (int i = 0; i < 25; ++i)
for (int j = 0; j < 25; ++j)
reach[i][j] = false;
for (int i = 1; i <= h; ++i)
for (int j = 1; j <= w; ++j)
{
cin >> map[i][j];
if (map[i][j] == '@')
{
map[i][j] = '.';
reach[i][j] = true;
ans++;
q.push(point(i, j));
}
if (map[i][j] == '#')
{
reach[i][j] = true;
}
}
while (!q.empty())
{
point tmp = q.front();
q.pop();
for (int i = 0; i < 4; ++i)
{
int xx = tmp.x + dx[i];
int yy = tmp.y + dy[i];
if (xx > 0 && xx <= h && yy > 0 && yy <= w && !reach[xx][yy])
{
reach[xx][yy] = true;
ans++;
q.push(point(xx, yy));
}
}
}
cout << ans << endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: