2 条题解

  • 2
    @ 2024-8-18 1:10:17

    也是一道经典宽搜题,字符形式不好计算位置 所以我取巧 把岛屿和海洋对应替换成 1 和 0 .
    这道题的核心就在于 找到岛屿的时候 就把他以及附近的陆地全部标记成海洋
    同时记录已经搜过(其实不用 但是如果记录的话 貌似减少时间)
    同时 ans自加 算一个岛屿 如此下来就很简单了

    Code:

    #include <iostream>
    #include <algorithm>
    #include <cstring>
    #include <queue>
    #define int long long
    
    using namespace std;
    const int N = 1050;
    typedef pair<int , int> PII;
    
    int n , m;
    int g[N][N] , d[N][N] , ans;
    bool ch[N][N];
    queue<PII> q;
    
    void bfs(int x , int y)
    {
        q.push({x , y});
        int dx[] = {1 , 0 , -1 , 0} , dy[] = {0 , 1 , 0 , -1};
    
        while (!q.empty())
        {
            int x = q.front().first , y = q.front().second;
            q.pop();
    
            for (int i = 0 ; i < 4 ; i ++ )
            {
                int xx = x + dx[i] , yy = dy[i] + y;
                if (xx >= 0 && xx < n && yy >= 0 && yy < m && !ch[xx][yy] && g[xx][yy] == 1)
                {
                    ch[xx][yy] = true;
                    g[xx][yy] = 1;
                    q.push({xx , yy});
                }
            }
        }
    }
    
    signed main()
    {
        cin >> n >> m;
        for (int i = 0 ; i < n ; i ++ )
        {
            for (int j = 0 ; j < m ; j ++ )
            {
                char temp;
                cin >> temp;
                if (temp == '#') g[i][j] = 1;
                else g[i][j] = 0;
            }
        }
    
        for (int i = 0 ; i < n ; i ++ )
        {
            for (int j = 0 ; j < m ; j ++ ) 
            {
                if (g[i][j] == 1 && !ch[i][j])
                {
                    ch[i][j] = true;
                    bfs(i , j);
                    ans ++;
                }
            }
        }
    
        cout << ans << endl;
    
        return 0;
    }
    

    信息

    ID
    92
    时间
    1000ms
    内存
    256MiB
    难度
    10
    标签
    递交数
    5
    已通过
    3
    上传者