【代码随想录训练营】【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)
        
    
相关推荐
我想进大厂6 小时前
洛谷---P1629 邮递员送信
c++·算法·图论
triticale7 小时前
【数据结构】求有向图强连通分量的方法
数据结构·图论
啊阿狸不会拉杆10 小时前
人工智能数学基础(十)—— 图论
人工智能·python·数学·算法·图论
方方土3331 天前
ABC 404
数据结构·算法·图论
jia_jia_LL2 天前
备战蓝桥杯国赛第一天-atcoder-beginner-contest404
c++·算法·蓝桥杯·图论
freyazzr2 天前
Leetcode刷题 | Day51_图论03_岛屿问题02
数据结构·c++·算法·leetcode·深度优先·图论
qq_447429412 天前
数据结构与算法:图论——最短路径
c语言·数据结构·c++·图论
汉克老师3 天前
GESP2024年6月认证C++八级( 第三部分编程题(2)空间跳跃)
c++·算法·图论·gesp八级·gesp8级
qq_447429414 天前
数据结构与算法:图论——并查集
数据结构·算法·图论
freyazzr7 天前
Leetcode刷题 | Day50_图论02_岛屿问题01_dfs两种方法+bfs一种方法
数据结构·c++·算法·leetcode·深度优先·图论·广度优先