【代码随想录训练营】【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)
        
    
相关推荐
Orion嵌入式随想录20 小时前
算法训练 | 图论Part1 | 98.所有可达路径
算法·深度优先·图论
奔跑的乌龟_1 天前
P3469 : Tarjan 求割点以及割点的一些性质
算法·图论
mana飞侠1 天前
代码随想录算法训练营第63天:图论[1]
数据结构·学习·算法·图论
mana飞侠1 天前
代码随想录算法训练营第65天:图论3[1]
算法·图论
我就是菜鸡12292 天前
【代码随想录——图论——岛屿问题】
图论
Orion嵌入式随想录2 天前
算法训练 | 图论Part4 | 110.字符串接龙、105.有向图的完全可达性、106.岛屿的周长
算法·深度优先·图论
阿拉-M832 天前
代码随想录Day76(图论Part11)
算法·图论
white-cat9942 天前
2024暑假集训第三次考试
数据结构·c++·算法·图论
mana飞侠4 天前
代码随想录算法训练营第69天:图论7[1]
算法·图论
情系明明4 天前
c++学习 图论1
c++·学习·图论