当前位置:网站首页>剑指 Offer II 105. 岛屿的最大面积
剑指 Offer II 105. 岛屿的最大面积
2022-07-01 16:28:00 【彼淇梁】
剑指 Offer II 105. 岛屿的最大面积【中等题】
思路:【DFS】
每遇到一个岛,记录岛屿数量为1,同时以这个岛为中心向上下左右四个方向搜索相邻岛屿并记录岛屿数量,同时将这个岛炸沉(置为0),表示已搜索过。
当一个岛四个方向搜索完毕,更新最大岛屿数量,由于每个岛屿面积一样,所以最大岛屿数量即最大岛屿面积。
代码:
class Solution {
static int m;
static int n;
public int maxAreaOfIsland(int[][] grid) {
m = grid.length;
n = grid[0].length;
int ans = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] != 0){
ans = Math.max(ans,dfs(i,j,grid));
}
}
}
return ans;
}
public int dfs(int x,int y,int[][] grid){
if (x < 0 || y < 0 || x == m || y == n || grid[x][y] == 0){
return 0;
}
grid[x][y] = 0;
int[][] f = {
{
0,1},{
0,-1},{
-1,0},{
1,0}};
int cnt = 1;
for (int i = 0; i < 4; i++) {
int dx = x + f[i][0],dy = y + f[i][1];
cnt += dfs(dx,dy,grid);
}
return cnt;
}
}
边栏推荐
- Analysis of PostgreSQL storage structure
- 数据库系统原理与应用教程(004)—— MySQL 安装与配置:重置 MySQL 登录密码(windows 环境)
- 虚拟串口模拟器和串口调试助手使用教程「建议收藏」
- Concatenate strings to get the result with the smallest dictionary order
- How wild are hackers' ways of making money? CTF reverse entry Guide
- SystemVerilog-结构体(二)
- [live broadcast appointment] database obcp certification comprehensive upgrade open class
- 免费抽奖 | 《阿巴豆》探索未来系列盲盒数字版权作品全网首发!
- 拼接字符串,得到字典序最小的结果
- Redis6.0 新功能
猜你喜欢
C语言输入/输出流和文件操作
为国产数据库添砖加瓦,StoneDB 一体化实时 HTAP 数据库正式开源!
EndeavourOS移动硬盘安装
Graduation season | Huawei experts teach the interview secret: how to get a high paying offer from a large factory?
Installation and use of sqoop
Basic use of MySQL
Today, at 14:00, 15 ICLR speakers from Hong Kong University, Beihang, Yale, Tsinghua University, Canada, etc. continue!
你还在用收费的文档管理工具?我这有更牛逼的选择!完全免费
Redis Distributed Lock
How to restore the system of Sony laptop
随机推荐
Stegano in the world of attack and defense
今天14:00 | 港大、北航、耶鲁、清华、加大等15位ICLR一作讲者精彩继续!
Germany if was crowned with many awards. How strong is this pair of headphones? In depth evaluation of yinpo GTW 270 hybrid
Activity的生命周期和启动模式详解
sql刷题1050. 合作过至少三次的演员和导演
How to restore the system with one click on Lenovo laptop
Determine whether the linked list is a palindrome linked list
Redis Distributed Lock
Bugku's file contains
Redis 分布式鎖
How to cancel automatic search and install device drivers for laptops
数据库系统原理与应用教程(005)—— yum 离线安装 MySQL5.7(Linux 环境)
EndeavourOS移动硬盘安装
Zabbix2.2 monitoring system and application log monitoring alarm
Graduation season | Huawei experts teach the interview secret: how to get a high paying offer from a large factory?
[live broadcast appointment] database obcp certification comprehensive upgrade open class
【直播预约】数据库OBCP认证全面升级公开课
巴比特 | 元宇宙每日必读:奈雪币、元宇宙乐园、虚拟股票游戏...奈雪的茶这波“操作拉满”的营销活动你看懂了吗?...
游戏行业安全选择游戏盾,效果怎么样?
Redis6.0 new features