zoukankan      html  css  js  c++  java
  • [leetcode]python 695. Max Area of Island

    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
    Object-C中使用NSKeyedArchiver归档(将各种类型的对象存储到文件中)
    转-- iOS 30多个iOS常用动画,带详细注释
    转-ios设备唯一标识获取策略
    微信授权
    Windows服务Demo
    查询某个时间段在另一个时间段里面的时间
    微服务官方文档链接
    c# html 转word
    Unreal4 入门(配置)
  • 原文地址:https://www.cnblogs.com/ruoh3kou/p/8698851.html
Copyright © 2011-2022 走看看