当前位置:网站首页>剑指 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;
}
}
边栏推荐
- 想做软件测试的女孩子看这里
- Is the programmer's career really short?
- Germany if was crowned with many awards. How strong is this pair of headphones? In depth evaluation of yinpo GTW 270 hybrid
- Judge whether a binary tree is a balanced binary tree
- Go 语言错误处理为什么更推荐使用 pkg/errors 三方库?
- China BMS battery management system Market Research Report (2022 Edition)
- Go language source level debugger delve
- How to use F1 to F12 correctly on laptop keyboard
- 今天14:00 | 港大、北航、耶鲁、清华、加大等15位ICLR一作讲者精彩继续!
- SQL question brushing 586 Customers with the most orders
猜你喜欢

博睿数据一体化智能可观测平台入选中国信通院2022年“云原生产品名录”

Internet News: "20220222" get together to get licenses; Many products of Jimi have been affirmed by consumers; Starbucks was fined for using expired ingredients in two stores

C language input / output stream and file operation

Alibaba cloud, Zhuoyi technology beach grabbing dialogue AI

How to solve the problem that the battery icon of notebook computer does not display

PR basic clip operation / video export operation

How to cancel automatic search and install device drivers for laptops

Installation and use of sqoop

Stegano in the world of attack and defense

C语言输入/输出流和文件操作
随机推荐
数据库系统原理与应用教程(005)—— yum 离线安装 MySQL5.7(Linux 环境)
Red team Chapter 10: ColdFusion the difficult process of deserializing WAF to exp to get the target
Zabbix2.2 monitoring system and application log monitoring alarm
Authentication processing in interface testing framework
Redis distributed lock
FRP intranet penetration, reverse proxy
单例模式的懒汉模式跟恶汉模式的区别
数据库系统原理与应用教程(004)—— MySQL 安装与配置:重置 MySQL 登录密码(windows 环境)
Redis 分布式鎖
如何使用 etcd 实现分布式 /etc 目录
What is the digital transformation of manufacturing industry
【Kotlin】高阶函数介绍
游戏行业安全选择游戏盾,效果怎么样?
Babbitt | yuan universe daily must read: Naixue coin, Yuan universe paradise, virtual stock game Do you understand Naixue's tea's marketing campaign of "operation pull full"
How to maintain the laptop battery
Transition technology from IPv4 to IPv6
Go 语言错误处理为什么更推荐使用 pkg/errors 三方库?
C language input / output stream and file operation
判断链表是否是回文链表
软件工程导论——第六章——详细设计