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.

在矩阵中找相连起来的最大的1s串(上下左右) 并计数返回

自己写的dfs:

def finded(x, y, nums):
ans2 = 1
if nums[x][y] == 0:
return 0
nums[x][y] = 0
if x - 1 >= 0:
ans2 += finded(x - 1, y, nums)
if x + 1 < len(nums):
ans2 += finded(x + 1, y, nums)
if y + 1 < len(nums[0]):
ans2 += finded(x, y + 1, nums)
if y - 1 >= 0:
ans2 += finded(x, y - 1, nums)
return ans2

class Solution:
def findMaxConsecutiveOnes(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
r = len(nums)
c = len(nums[0])
ans = 0
for i in range(r):
for j in range(c):
if nums[i][j] == 0:
continue
res = finded(i, j, nums)
if ans < res:
ans = res
return ans

题解中的DfS算法:

class Solution(object):
def maxAreaOfIsland(self, grid):
seen = set()

def area(r, c):
if not (0 <= r < len(grid) and 0 <= c < len(grid[0])
and (r, c) not in seen and grid[r][c]):
return 0
seen.add((r, c))
return (1 + area(r + 1, c) + area(r - 1, c) +
area(r, c - 1) + area(r, c + 1))

return max(area(r, c)
for r in range(len(grid))
for c in range(len(grid[0])))

最新文章

  1. php use memcached in ubuntu 14.04
  2. springMVC含文件上传调用ajax无法连接后台
  3. CSS 文字垂直居中
  4. arcgis_engine_c++_runtime_r6034_error
  5. Page Scroll Effects - 简单的页面滚动效果
  6. opencv - haar人脸特征的训练
  7. Linux下Nginx的安装与配置
  8. 性能测试之Windows常见性能计数器
  9. 【Ural】【1057】Amount of degrees
  10. Node.js开发指南中的例子(mysql版)
  11. poj2443(简单的状态压缩)
  12. [置顶] SQL注入安全分析
  13. passwd总结
  14. 模拟Paxos算法及其简单学习总结
  15. B20J_1419_Red Is Good_期望DP
  16. python学习——读取染色体长度(六:读取含有染色体长度的文件)
  17. Spring源码学习-容器BeanFactory(三) BeanDefinition的创建-解析Spring的默认标签
  18. Kafka设计解析(七)- Kafka Stream
  19. 局域网主机A向主机B发送ip数据报的过程
  20. Windows10上强制Visual Studio以管理员身份运行

热门文章

  1. delphi hook alt+F4 ctrl+delete+alt win键等
  2. 教你做一个牛逼的DBA(在大数据下)
  3. Yolov3代码分析与训练自己数据集
  4. win2008环境mysql主从配置
  5. happy machine learning(First One)
  6. 带你手写基于 Spring 的可插拔式 RPC 框架(一)介绍
  7. 给VS设置代码创建人的宏
  8. NMI watchdog: BUG: soft lockup - CPU#0 stuck for 22s!
  9. 风险:隐蔽权限修改导致rgw服务中断
  10. leetcode的Hot100系列--136. 只出现一次的数字