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])))

  • 相关阅读:
    MyEclipe 配置 ivy 插件
    PHP 向 MySql 中数据修改操作时,只对数字操作有效,非数字操作无效,怎么办?
    Hadoop 中 Eclipse 的配置
    Hadoop 配置好hive,第一次在conf能进入,第二次就不行了,怎么办?
    7系列FPGA远程更新方案-QuickBoot(转)
    Serial interface (RS-232)
    Linux下安装微信(转)
    《图解HTTP》读书笔记(转)
    《图解TCP/IP》读书笔记(转)
    7 Serial Configuration 理解(三)
  • 原文地址:https://www.cnblogs.com/ruoh3kou/p/8698851.html
Copyright © 2011-2022 走看看