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;
}
点赞