news 2026/6/10 1:11:41

代码随想录 695.岛屿的最大面积

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
代码随想录 695.岛屿的最大面积

思路:

1.注意题目中的每座岛屿只能由水平方向和竖直方向相邻的陆地连接形成。

2.这题也是bfs、dfs的基础题目,就是搜索每个岛屿上“1”的数量,然后取一个最大的。

一、DFS:

附代码:

class Solution { public int maxAreaOfIsland(int[][] grid) { int res = 0; for(int i = 0;i < grid.length;i++){ for(int j = 0;j < grid[i].length;j++){ if(grid[i][j] == 1){ //发现新岛屿 res = Math.max(res,dfs(grid,i,j)); //将整个岛屿标记为已访问,统计岛屿面积并求最大岛屿面积 } } } return res; } private int dfs(int[][] grid,int i,int j){ if(i < 0 || j < 0 || i >= grid.length || j >= grid[i].length || grid[i][j] == 0){ return 0; } //当前节点 int count = 1; //将当前岛屿标记为已访问(沉没岛屿,改为0) grid[i][j] = 0; //向四个方向递归探索 count += dfs(grid,i - 1,j); count += dfs(grid,i + 1,j); count += dfs(grid,i,j + 1); count += dfs(grid,i,j - 1); return count; } }

二、BFS:

附代码:

class Solution { public int maxAreaOfIsland(int[][] grid) { int res = 0; for(int i = 0;i < grid.length;i++){ for(int j = 0;j < grid[0].length;j++){ if(grid[i][j] == 1){ res = Math.max(res,bfs(grid,i,j)); } } } return res; } private int bfs(int[][] grid,int i,int j){ int[] dx = {1,-1,0,0}; int[] dy = {0,0,1,-1}; LinkedList<int[]> queue = new LinkedList<>(); queue.add(new int[] {i,j}); grid[i][j] = 0; int count = 1; while(!queue.isEmpty()){ int[] cur = queue.remove(); for(int index = 0;index < 4;index++){ int nx = cur[0] + dx[index],ny = cur[1] + dy[index]; if(nx >= 0 && nx < grid.length && ny >= 0 && ny < grid[0].length && grid[nx][ny] == 1){ grid[nx][ny] = 0; count += 1; queue.add(new int[] {nx,ny}); } } } return count; } }
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/6/9 18:48:38

如何快速在K8s上部署Apache Doris:3步搭建高性能数据平台

如何快速在K8s上部署Apache Doris&#xff1a;3步搭建高性能数据平台 【免费下载链接】doris Apache Doris is an easy-to-use, high performance and unified analytics database. 项目地址: https://gitcode.com/gh_mirrors/dori/doris Apache Doris作为一款高性能的统…

作者头像 李华
网站建设 2026/6/9 20:03:43

Bruno:5大核心优势打造企业级Flutter UI组件解决方案

Bruno&#xff1a;5大核心优势打造企业级Flutter UI组件解决方案 【免费下载链接】bruno An enterprise-class package of Flutter components for mobile applications. ( Bruno 是基于一整套设计体系的 Flutter 组件库。) 项目地址: https://gitcode.com/gh_mirrors/bru/br…

作者头像 李华
网站建设 2026/6/9 7:08:37

GraphQL Editor实战:7个立竿见影的性能提升技巧

GraphQL Editor实战&#xff1a;7个立竿见影的性能提升技巧 【免费下载链接】graphql-editor &#x1f4fa; Visual Editor & GraphQL IDE. 项目地址: https://gitcode.com/gh_mirrors/gr/graphql-editor 在处理大规模GraphQL Schema时&#xff0c;性能优化是每个开…

作者头像 李华
网站建设 2026/6/5 15:13:27

技术领跑变合规领跑,赛米控斩获燃气炒菜机3C“双气源“双证

作为商用智能炒菜机国家标准起草单位&#xff0c;赛米控首批通过燃气燃烧器具3C强制认证&#xff0c;推动行业规范升级随着国家对燃气燃烧器具监管力度升级&#xff0c;商用燃气炒菜机3C强制认证成为行业"入场券"。作为《商用智能炒菜机》国家标准起草单位之一&#…

作者头像 李华
网站建设 2026/6/9 14:16:20

KoboldCPP完整使用指南:从零开始掌握AI文本生成神器

KoboldCPP完整使用指南&#xff1a;从零开始掌握AI文本生成神器 【免费下载链接】koboldcpp A simple one-file way to run various GGML and GGUF models with KoboldAIs UI 项目地址: https://gitcode.com/gh_mirrors/ko/koboldcpp KoboldCPP是一款基于llama.cpp开发的…

作者头像 李华