zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    POJ 3258 (NOIP2015 D2T1跳石头)
    POJ 3122 二分
    POJ 3104 二分
    POJ 1995 快速幂
    409. Longest Palindrome
    389. Find the Difference
    381. Insert Delete GetRandom O(1)
    380. Insert Delete GetRandom O(1)
    355. Design Twitter
    347. Top K Frequent Elements (sort map)
  • 原文地址:https://www.cnblogs.com/rainydays/p/2844705.html
Copyright © 2011-2022 走看看