演算法23-------島嶼的最大面積 LeetCode 695

來源:互聯網
上載者:User

標籤:最大的   別人   div   leetcode   elf   bsp   lan   超過   isl   

一、題目:

給定一個包含了一些 0 和 1的非空二維數組 grid , 一個 島嶼 是由四個方向 (水平或垂直) 的 1 (代表土地) 構成的組合。你可以假設二維矩陣的四個邊緣都被水包圍著。

找到給定的二維數組中最大的島嶼面積。(如果沒有島嶼,則返回面積為0。)

樣本 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]]

對於上面這個給定矩陣應返回 6。注意答案不應該是11,因為島嶼只能包含水平或垂直的四個方向的‘1’。

樣本 2:

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

對於上面這個給定的矩陣, 返回 0

注意: 給定的矩陣grid 的長度和寬度都不超過 50。

 

二、思路:【來自LeetCode別人的解法】

遍曆矩陣,遇到 grid [i] [j] = 1時,就算值【採用dfs來算】

dfs : 先將grid [i] [j] 置0,然後再 return 1 + dfs [i-1] [j] + dfs [i+1] [j] +dfs [i] [j-1] +dfs [i] [j+1]

 

三、代碼:
    def maxAreaOfIsland(self, grid):        """        :type grid: List[List[int]]        :rtype: int        """        if not grid:            return 0        l,h = len(grid),len(grid[0])                def dfs(i,j):            if 0 <= i < l and 0 <= j < h and grid[i][j]:                grid[i][j] = 0                return 1 + dfs(i-1,j) + dfs(i+1,j) +dfs(i,j-1) + dfs(i,j+1)            return 0                    result = [dfs(i,j) for i in range(l) for j in range(h) if grid[i][j]]        return max(result) if result else 0

 

演算法23-------島嶼的最大面積 LeetCode 695

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.