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

图论岛屿问题DFS+BFS

leetcode 200 岛屿问题

class Solution {//定义对应的方向boolean [][] visited;int dir[][]={{0,1},{1,0},{-1,0},{0,-1}};public int numIslands(char[][] grid) {//对应的二维数组int count=0;visited=new boolean[grid.length][grid[0].length];for (int i = 0; i < grid.length; i++) {for (int j = 0; j < grid[0].length; j++) {if (visited[i][j] == false && grid[i][j]=='1') {count++;dfs(grid,i,j);}}}return count;}public  void dfs(char[][]grid,int x,int y){if (visited[x][y]==true||grid[x][y]=='0'){return;}visited[x][y]=true;for (int i = 0; i <4; i++) {int nextX=x+dir[i][0];int nextY=y+dir[i][1];if (nextY<0||nextX<0||nextX>=grid.length||nextY>=grid[0].length){continue;}dfs(grid,nextX,nextY);}}
}

BFS代码

class  Solution{boolean[][] visited;int move[][]={{0,1},{0,-1},{1,0},{-1,0}};public int numIslands(char[][] grid) {int res=0;visited=new boolean[grid.length][grid[0].length];for (int i = 0; i < grid.length; i++) {for (int j = 0; j < grid[0].length; j++) {if (!visited[i][j]&&grid[i][j]=='1'){bfs(grid,i,j);res++;}}}return  res;}public  void bfs(char [][] grid,int x,int y){Deque<int[]> queue=new ArrayDeque<>(); //创建一个队列queue.offer(new int[]{x,y});visited[x][y]=true;while (!queue.isEmpty()){int []cur=queue.poll();int m=cur[0];int n=cur[1];for (int i=0;i<4;i++){int nextx=m+move[i][0];int nexty=n+move[i][1];if (nextx<0||nextx==grid.length||nexty<0||nexty==grid[0].length){continue;}if (!visited[nextx][nexty]&&grid[nextx][nexty]=='1'){queue.offer(new int[]{nextx,nexty});visited[nextx][nexty]=true;}}}}
http://www.lryc.cn/news/148207.html

相关文章:

  • Cypress web自动化windows环境npm安装Cypress
  • CentOS7.9设置ntp时间同步
  • 36、springboot --- 对 tomcat服务器 和 undertow服务器 配置访客日志
  • MySQL表的增删改查
  • yolov3
  • 基于低代码/无代码工具构建 BI 应用程序
  • Servlet与过滤器
  • 微信小程序开发实战记录
  • 防破解暗桩思路:检查菜单是否被非法修改过源码
  • IDEA使用Docker插件
  • [前端] vue使用Mousetrap.js实现快捷键
  • 如何查询Oracle的字符集
  • C语言每日一练------------Day(7)
  • Meta语言模型LLaMA解读:模型的下载部署与运行代码
  • 人生中的孤独
  • 掌握Spring框架核心组件:深入探讨IOC、AOP、MVC及注解方式面试指南【经验分享】
  • 代码随想录算法训练营第37天 | ● 738.单调递增的数字 ● 968.监控二叉树 ● 总结
  • SOPC之NIOS Ⅱ实现电机转速PID控制(调用中断函数)
  • ElasticSearch安装为Win11服务
  • ransac拟合平面,代替open3d的segment_plane
  • Docker技术--Docker镜像管理
  • 生态环境保护3D数字展厅提供了一个线上环保知识学习平台
  • OPENCV实现计算描述子
  • Android View动画之LayoutAnimation的使用
  • 低代码与低代码平台的概念解析
  • 玩转Mysql系列 - 第8篇:详解排序和分页(order by limit),及存在的坑
  • Django实现音乐网站 ⒂
  • 爬虫逆向实战(二十八)--某税网第一步登录
  • 【Dots之003】SystemAPI.Query相关基础笔记
  • vue v-for 例子