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

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

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

需强化知识点

  • 深度搜索和广度搜索

题目

99. 岛屿数量

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

  • 深度搜索
  • 广度搜索:此处用 [] 作为待遍历队列也可,que(append,popleft)
import collectionsdef 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_xnext_y = y + add_yif next_x < 0 or next_x >= len(grid) or next_y < 0 or next_y >= len(grid[0]):continueif not visited[next_x][next_y] and grid[next_x][next_y]:visited[next_x][next_y] = Truedfs(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] = Truewhile 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_xnext_y = cur_y + add_yif next_x < 0 or next_x >= len(grid) or next_y < 0 or next_y >= len(grid[0]):continueif not visited[next_x][next_y] and grid[next_x][next_y]:que.append([next_x, next_y])visited[next_x][next_y] = Truetmp = 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] = Trueresult += 1bfs(grid, visited, i, j)print(result)
http://www.lryc.cn/news/387878.html

相关文章:

  • 【动态规划】139. 单词拆分
  • 【C++】空指针访问成员函数
  • Linux的IO易错点总结
  • 【Android面试八股文】说一说你对Android中的Context的理解吧
  • AI在音乐创作中的角色:创造还是毁灭?
  • [深入理解DDR] 总目录
  • 模板方法模式在金融业务中的应用及其框架实现
  • leetcode347.前k个高频元素
  • c++(二)
  • 基于PHP的初中数学题库管理系统
  • WDG看门狗
  • zabbix server client 安装配置
  • Unity关于Addressables.Release释放资源内存问题
  • 运算放大器(运放)带宽和带宽平坦度
  • npm常用命令使用与事件案例
  • Spring Boot中的定时任务调度
  • Hadoop3:MapReduce中的ETL(数据清洗)
  • python解锁图片相似度的神奇力量
  • TensorFlow 的原理与使用
  • [数据库]事务的隔离级别存储引擎
  • 使用nvm切换node版本时报错:exit status 1解决办法
  • Kafka~高吞吐量设计
  • STM32小项目———感应垃圾桶
  • 嵌入式MCU平台汇总
  • C#udpClient组播
  • 《昇思25天学习打卡营第14天 | 昇思MindSpore基于MindNLP+MusicGen生成自己的个性化音乐》
  • 新奥集团校招面试经验分享、测评笔试题型分析
  • 【推荐】Prometheus+Grafana企业级监控预警实战
  • 深度剖析:前端如何驾驭海量数据,实现流畅渲染的多种途径
  • AI时代,你的工作会被AI替代吗?