【代码随想录训练营】【Day 65】【图论-2】| 卡码 99

【代码随想录训练营】【Day 65】【图论-2】| 卡码 99

需强化知识点

  • 深度搜索和广度搜索

题目

99. 岛屿数量

思想:遍历到为1的节点,再搜索标记,每遇到新的陆地节点,增加计数

  • 深度搜索
  • 广度搜索:此处用 [] 作为待遍历队列也可,que(append,popleft)
python 复制代码
import collections

def dfs(grid, visited, x, y):
    dirs = [[0, 1], [0, -1], [1, 0], [-1, 0]]
    for add_x, add_y in dirs:
        next_x = x + add_x
        next_y = y + add_y
        
        if next_x < 0 or next_x >= len(grid) or next_y < 0 or next_y >= len(grid[0]):
            continue
        
        if not visited[next_x][next_y] and grid[next_x][next_y]:
            visited[next_x][next_y] = True
            dfs(grid, visited, next_x, next_y)

def bfs(grid, visited, x, y):
    dirs = [[0, 1], [0, -1], [1, 0], [-1, 0]]
    que = collections.deque()
    # que = []
    que.append([x, y])
    visited[x][y] = True
    while que:
        # cur = que.pop()
        cur = que.popleft()
        cur_x = cur[0]
        cur_y = cur[1]
        for add_x, add_y in dirs:
            next_x = cur_x + add_x
            next_y = cur_y + add_y
        
            if next_x < 0 or next_x >= len(grid) or next_y < 0 or next_y >= len(grid[0]):
                continue
        
            if not visited[next_x][next_y] and grid[next_x][next_y]:
                que.append([next_x, next_y])
                visited[next_x][next_y] = True
        
        

tmp = list(map(int, input().split()))
m, n = tmp[0], tmp[1]

grid = [[0]*n for _ in range(m)]
visited = [[False]*n for _ in range(m)]
for i in range(m):
    tmp = list(map(int, input().split()))
    for j in range(n):
        grid[i][j] = tmp[j]

result = 0
for i in range(m):
    for j in range(n):
        if not visited[i][j] and grid[i][j]:
            visited[i][j] = True
            result += 1
            bfs(grid, visited, i, j)

print(result)
        
    
相关推荐
Paper Clouds1 天前
代码随想录|图论|15并查集理论基础
数据结构·算法·leetcode·深度优先·图论
Paper Clouds1 天前
代码随想录|图论|14有向图的完全可达性
数据结构·算法·深度优先·图论·宽度优先
泛舟起晶浪4 天前
相对成功与相对失败--dp
算法·动态规划·图论
你的冰西瓜5 天前
C++ 中最短路算法的详细介绍
c++·算法·图论·最短路
Swift社区5 天前
Swift 图论实战:DFS 算法解锁 LeetCode 323 连通分量个数
算法·swift·图论
浩瀚星辰20245 天前
图论基础算法:DFS、BFS、并查集与拓扑排序的Java实现
java·算法·深度优先·图论
lcg_magic7 天前
图论系列(一):基础概念与术语解析
图论
127_127_12711 天前
2025 FJCPC 复建 VP
数据结构·图论·模拟·ad-hoc·分治·转化
wwer14252636311 天前
数学建模_图论
数学建模·图论
ysa05103011 天前
Dijkstra 算法#图论
数据结构·算法·图论