博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Leetcode]695. Max Area of Island
阅读量:6976 次
发布时间:2019-06-27

本文共 1430 字,大约阅读时间需要 4 分钟。

Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.

Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area is 0.)

Example 1:

[[0,0,1,0,0,0,0,1,0,0,0,0,0], [0,0,0,0,0,0,0,1,1,1,0,0,0], [0,1,1,0,1,0,0,0,0,0,0,0,0], [0,1,0,0,1,1,0,0,1,0,1,0,0], [0,1,0,0,1,1,0,0,1,1,1,0,0], [0,0,0,0,0,0,0,0,0,0,1,0,0], [0,0,0,0,0,0,0,1,1,1,0,0,0], [0,0,0,0,0,0,0,1,1,0,0,0,0]]

Given the above grid, return 6. Note the answer is not 11, because the island must be connected 4-directionally.

 

Example 2:

[[0,0,0,0,0,0,0,0]]

Given the above grid, return 0.

 

Note: The length of each dimension in the given grid does not exceed 50.

 

思路:深度优先搜索。从第一行第一个开始遍历整个数组,如果某个位置的值是 1 ,那么就开始深度优先搜索。

在深度优先搜索中,我们先要看看与该位置连通有几种可能的情况,很明显是4种,即上下左右。所以我们得用

个循环来遍历这四种可能的情况。如果上或下或左或右的值是1,我们就用递归函数递归上或下或左或右的位置,

求解他们连通的情况。

 

1 class Solution { 2     private int sum = 0,maxSum = 0; 3     public int maxAreaOfIsland(int[][] grid) { 4         for (int i=0;i
=0&&grid[i-1][j]==1)18 dfs(grid,i-1,j);19 if (i+1
=0&&grid[i][j-1]==1)22 dfs(grid,i,j-1);23 if (j+1
maxSum){26 maxSum = sum;27 }28 29 }30 }

 

转载于:https://www.cnblogs.com/David-Lin/p/7749633.html

你可能感兴趣的文章
Centos运行级别和开机过程
查看>>
Linux 装B之作酷炫小工具
查看>>
Citrix Avalon安装实验手册之一----Avalon概述及实验环境准备
查看>>
动态表单构建器——建造者模式
查看>>
Android 自动化测试
查看>>
MySQL 5.5 服务器变量详解(二)
查看>>
bootstrap table
查看>>
CentOS 7 yum 安装 MySQL5.7
查看>>
企业网络翻译官——DNS
查看>>
RocketMQ3.2.2生产者发送消息自动创建Topic队列数无法超过4个
查看>>
USG防火墙telnet实验
查看>>
[给12306支招]取消车票预订-采用全额预售(充值)
查看>>
linux下使profile和.bash_profile立即生效的方法
查看>>
Operations Manager 2012 SP1配置部署系列之(二) SCOM监控SCVMM
查看>>
父域与子域之的信任关系
查看>>
Android中后台定时任务实现,即时数据同步问题思考!
查看>>
开启笔记本win7的虚拟热点,让你的本本变成wifi
查看>>
ETL数据抽取策略
查看>>
Python学习day5作业-ATM和购物商城
查看>>
Kubernetes基于Metrics Server的HPA
查看>>