当前位置: 首页 > news >正文

day51 第十一章:图论part02

99. 岛屿数量 深搜

每一块的上下左右都遍历过了之后,这块陆地就遍历完了。是深搜,不是广搜

深搜:递归

def dfs():

        if .....:

                终止条件

        dfs(子节点)

directions = [[0,1],[1,0],[0,-1],[-1,0]]

def dfs(grid, visited, x, y):
    if grid[x][y] == 0 or visited[x][y]:
        return
    visited[x][y] = True
    for i in range(4):
        next_x = x + directions[i][0]
        next_y = y + directions[i][1]
        if next_x < 0 or next_x >=n or next_y < 0 or next_y >= m:
            continue
        dfs(grid, visited, next_x, next_y)
    
    
if __name__ == '__main__':
    n, m = map(int, input().split())
    
    grid = []
    for _ in range(n):
        grid.append(list(map(int, input().split())))
        
    visited = [[False]*m for _ in range(n)]
    res = 0
    
    for i in range(n):
        for j in range(m):
            if grid[i][j] == 1 and not visited[i][j]:
                res += 1 
                dfs(grid, visited, i, j)
    
    print(res)
    

99. 岛屿数量 广搜

广搜用队列(deque),

先加进去第一个节点

while que:

        cur = que.popleft()

        for cur_child in cur_children:

                que.append(cur_child)

        

from collections import deque
directions = [[0,1],[1,0],[0,-1],[-1,0]]

def bfs(grid, visited, x, y):
    que = deque([])
    que.append([x,y])
    visited[x][y] = True
    while que:
        cur_x, cur_y = que.popleft()
        for i in range(4):
            next_x = cur_x + directions[i][0]
            next_y = cur_y + directions[i][1]
            if next_x < 0 or next_x >=n or next_y < 0 or next_y >= m:
                continue
            elif grid[next_x][next_y] == 1 and not visited[next_x][next_y]:
                que.append([next_x, next_y])
                visited[next_x][next_y] = True
            
    
if __name__ == '__main__':
    n, m = map(int, input().split())
    
    grid = []
    for _ in range(n):
        grid.append(list(map(int, input().split())))
        
    visited = [[False]*m for _ in range(n)]
    res = 0
    
    for i in range(n):
        for j in range(m):
            if grid[i][j] == 1 and not visited[i][j]:
                res += 1 
                bfs(grid, visited, i, j)
    
    print(res)
    

100. 岛屿的最大面积

dfs

# dfs,bfs都行
# dfs
directions = [[0,1],[1,0],[0,-1],[-1,0]]
max_area = 0
area = 0


def dfs(grid, visited, x, y):
    global area
    global max_area

    if grid[x][y] == 0 or visited[x][y] == True:
        return
    visited[x][y] = True
    area += 1
    max_area = max(max_area, area)
    # print("area=", area)
    # print("max_area=", max_area)
    for i in range(4):
        next_x = x + directions[i][0]
        next_y = y + directions[i][1]
        if next_x < 0 or next_x >= n or next_y < 0 or next_y >= m:
            continue
        dfs(grid, visited, next_x, next_y)
        
if __name__ == "__main__":
    n,m = map(int, input().split())

    grid = []
    for _ in range(n):
        grid.append(list(map(int, input().split())))

    # n,m = 4, 5
    # grid = [[1,1,0,0,0],[1,1,0,0,0],[0,1,1,0,0],[0,0,0,1,1]]

    visited = [[False]*m for _ in range(n)]

    for i in range(n):
        for j in range(m):
            if grid[i][j] == 1 and not visited[i][j]:
                area = 0
                dfs(grid, visited, i, j)
    
    print(max_area)
    

bfs

# dfs,bfs都行
# bfs
from collections import deque
directions = [[0,1],[1,0],[0,-1],[-1,0]]

def bfs(grid, visited, x, y):
    area = 0
    que = deque()
    que.append([x,y])
    while que:
        cur_x, cur_y = que.popleft()
        if grid[cur_x][cur_y] == 1 and not visited[cur_x][cur_y]:
            area += 1
            visited[cur_x][cur_y] = True
            for i in range(4):
                next_x = cur_x + directions[i][0]
                next_y = cur_y + directions[i][1]
                if next_x < 0 or next_x >= n or next_y < 0 or next_y >=m:
                    continue
                # if grid[next_x][next_y] == 1 and not visited[next_x][next_y]:
                que.append([next_x, next_y])
            
    return area


       
if __name__ == "__main__":
    n,m = map(int, input().split())

    grid = []
    for _ in range(n):
        grid.append(list(map(int, input().split())))

    visited = [[False]*m for _ in range(n)]
    max_area = 0

    for i in range(n):
        for j in range(m):
            if grid[i][j] == 1 and not visited[i][j]:
                # area = 0
                # global max_area
                max_area = max(max_area, bfs(grid, visited, i, j))
    
    print(max_area)
    

相关文章:

  • 基于Matlab实现六自由度机械臂正逆运动仿真(源码)
  • 单片机简介
  • 2025常用的SEO工具有哪些?
  • PyTorch Lightning多GPU分布式日志介绍
  • (Xshell 8 + Xftp 8)下载安装miniconda至服务器指定目录+配置虚拟环境
  • K8S容器启动提示:0/2 nodes are available: 2 Insufficient cpu.
  • CSS 小技巧 —— CSS 实现 Tooltip 功能-鼠标 hover 之后出现弹层
  • 二分查找sql时间盲注,布尔盲注
  • 【翻译+论文阅读】DeepSeek-R1评测:粉碎GPT-4和Claude 3.5的开源AI革命
  • Kubernetes 最佳实践:Top 10 常见 DevOps/SRE 面试问题及答案
  • RTD2775QT/RTD2795QT瑞昱显示器芯片方案
  • 21vue3实战-----git husky和git commit规范
  • 大语言模型多代理协作(MACNET)
  • 计算机视觉中图像的基础认知
  • 二级等保对机房的要求
  • 集成学习(二):从理论到实战(附代码)
  • DeepSeek-R1 蒸馏 Qwen 和 Llama 架构 企业级RAG知识库
  • 侯捷 C++ 课程学习笔记:C++ 内存管理机制的深度剖析与实践
  • 石英表与机械表的世纪之争(Quartz vs. Mechanical Watches):瑞士钟表业的危机与重生(中英双语)
  • Ubuntu+Laravel+MQ+Supervisor队列系统搭建流程
  • 埃尔多安:愿在土耳其促成俄乌领导人会晤
  • 获派驻6年后,中国驻厄瓜多尔大使陈国友即将离任
  • 南方降水频繁暴雨连连,北方高温再起或现40°C酷热天气
  • 车载抬头显示爆发在即?业内:凭借市场和产业链优势,国内供应商实现反超
  • 沙青青评《通勤梦魇》︱“人机组合”的通勤之路
  • 王毅谈中拉论坛第四届部长级会议重要共识