2016.6.20

进入考试周...终于要开始复习程设了

先重新熟练一下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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值