poj1111

bfs

View Code
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <queue>
using namespace std;

#define maxn 30

struct Point
{
    int x, y;
} s;

int n, m;
int dir[8][2] =
{
{ 1, 0 },
{ 0, 1 },
{ -1, 0 },
{ 0, -1 },
{ 1, 1 },
{ -1, 1 },
{ 1, -1 },
{ -1, -1 } };
char map[maxn][maxn];
bool vis[maxn][maxn];

void input()
{
    for (int i = 0; i < n; i++)
        scanf("%s", map[i]);
}

bool in_map(Point &a)
{
    return a.x >= 0 && a.y >= 0 && a.x < n && a.y < m;
}

int cal(Point &a)
{
    int ret = 0;
    for (int i = 0; i < 4; i++)
    {
        Point b = a;
        b.x += dir[i][0];
        b.y += dir[i][1];
        if (!in_map(b) || map[b.x][b.y] == '.')
            ret++;
    }
    return ret;
}

int bfs()
{
    memset(vis, 0, sizeof(vis));
    queue<Point> q;
    q.push(s);
    vis[s.x][s.y] = true;
    int ans = cal(s);
    while (!q.empty())
    {
        Point a = q.front();
        q.pop();
        for (int i = 0; i < 8; i++)
        {
            Point b = a;
            b.x += dir[i][0];
            b.y += dir[i][1];
            if (in_map(b) && map[b.x][b.y] == 'X' && !vis[b.x][b.y])
            {
                q.push(b);
                ans += cal(b);
                vis[b.x][b.y] = true;
            }
        }
    }
    return ans;
}

int main()
{
//    freopen("t.txt", "r", stdin);
    while (scanf("%d%d%d%d", &n, &m, &s.x, &s.y), n | m | s.x | s.y)
    {
        s.x--;
        s.y--;
        input();
        printf("%d\n", bfs());
    }
    return 0;
}

 

posted @ 2013-01-04 19:21  金海峰  阅读(264)  评论(0编辑  收藏  举报