淹没的岛屿 bfs

#include<bits/stdc++.h>

#define x first
#define y second

using namespace std;

typedef pair<int,int> PII;
const int N = 1e3 + 9;

int n ;
char g[N][N];
bool st[N][N];
PII q[N * N];
int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, 1, 0, -1};

void bfs(int sx, int sy, int &total, int &bound)
{
    int hh = 0, tt = 0;
    q[0] = {sx, sy};
    st[sx][sy] = true;
    
    while(hh <= tt)  // 当队列不空的时候
    {
            PII t = q[hh ++];
            
            total ++ ;
            bool is_bound = false;
            for(int i = 0; i < 4; i ++)
            {
                int x = t.x + dx[i], y = t.y + dy[i];
                if(x < 0 || x >= n || y < 0 || y >= n) continue;
                if(st[x][y]) continue;  //已经被遍历过需要跳过
                if(g[x][y] == '.')// 如果是海洋的话也要进行跳过
                {
                    is_bound = true;
                    continue;
                }
                
                q[ ++ tt] = {x, y};
                st[x][y] = true ;
            }
        
            if(is_bound) bound ++ ;
    }
}

int main()
{
    scanf("%d", &n);
    
    for(int i = 0; i < n; i ++) scanf("%s", g[i]);
    
    int cnt = 0;
    
    for(int i = 0; i < n; i ++)
        for(int j = 0; j < n; j ++)
            if(!st[i][j] && g[i][j] == '#')  //如果当前位置没有被遍历过且当前位置是陆地
            {
                int total = 0, bound = 0;
                bfs(i, j, total, bound);
                if(total == bound) cnt ++ ; 
            }
            // total 表示岛屿的数量
            // bound 表示海洋的地方

    printf("%d\n", cnt );
    return 0;
}

### 关于 DFS 和 BFS 的示例题目及解答 #### 题目描述 给定一个由字符 '1'(陆地)和 '0'(水)组成的二维网格 `grid` ,计算岛屿的数量。岛屿总是被水包围,并且每座岛屿只能由水平方向或竖直方向上相邻的陆地连接形成。 此外,可以假设该网格的四周均被水包围[^2]。 #### 示例输入输出 对于如下输入: ```python grid = [ ["0", "0", "1", "0", "0", "0", "0", "1", "0", "0", "0", "0", "0"], ["0", "0", "0", "0", "0", "0", "0", "1", "1", "1", "0", "0", "0"], ["0", "1", "1", "0", "1", "0", "0", "0", "0", "0", "0", "0", "0"], ["0", "1", "0", "0", "1", "1", "0", "0", "1", "0", "1", "0", "0"], ["0", "1", "0", "0", "1", "1", "0", "0", "1", "1", "1", "0", "0"], ["0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "1", "0", "0"], ["0", "0", "0", "0", "0", "0", "0", "1", "1", "1", "0", "0", "0"], ["0", "0", "0", "0", "0", "0", "0", "1", "1", "0", "0", "0", "0"] ] ``` 期望输出为:6 解释:答案不是 11,因为岛屿只能包含水平或垂直这四个方向上的 '1'。 #### 使用 BFS 实现解法 通过广度优先搜索 (BFS),可以从每一个未访问过的 '1' 开始遍历整个岛屿,并将其标记为已访问过的位置设置成 '0' 或其他非 '1' 值来防止重复计数。 ```python from collections import deque def numIslands_bfs(grid): if not grid or not grid[0]: return 0 rows, cols = len(grid), len(grid[0]) count = 0 for i in range(rows): for j in range(cols): if grid[i][j] == "1": bfs(i, j, grid) count += 1 return count def bfs(x, y, grid): queue = deque([(x,y)]) while queue: cur_x, cur_y = queue.popleft() directions = [(0,-1),(0,1),(-1,0),(1,0)] for dx, dy in directions: nx, ny = cur_x + dx, cur_y + dy if 0 <= nx < len(grid) and \ 0 <= ny < len(grid[0]) and \ grid[nx][ny] == "1": grid[nx][ny] = "0" queue.append((nx, ny)) ``` #### 使用 DFS 实现解法 深度优先搜索 (DFS) 同样适用于解决此类问题,在遇到一个新的 '1' 时启动递归函数淹没整片相连区域直到无法继续扩展为止。 ```python def numIslands_dfs(grid): if not grid or not grid[0]: return 0 rows, cols = len(grid), len(grid[0]) count = 0 for i in range(rows): for j in range(cols): if grid[i][j] == "1": dfs(i, j, grid) count += 1 return count def dfs(x, y, grid): if x<0 or y<0 or x>=len(grid) or y>=len(grid[0]) or grid[x][y]=="0": return grid[x][y]="0" dfs(x+1, y, grid) dfs(x-1, y, grid) dfs(x, y+1, grid) dfs(x, y-1, grid) ``` 这两种方法都能有效地解决问题并返回正确的结果数量。值得注意的是,在实际应用中选择哪种方式取决于具体场景和个人偏好;然而,在某些情况下使用 DFS 可能在面试过程中显得更加突出[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值