Max Area of Island

You are given an m x n binary matrix grid. 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.

The area of an island is the number of ce…


This content originally appeared on DEV Community 👩‍💻👨‍💻 and was authored by SalahElhossiny

You are given an m x n binary matrix grid. 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.

The area of an island is the number of cells with a value 1 in the island.

Return the maximum area of an island in grid. If there is no island, return 0.


class Solution:
    def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
        ROWS, COLS = len(grid), len(grid[0])
        visit = set()

        def dfs(r, c):
            if (
                r < 0
                or r == ROWS
                or c < 0
                or c == COLS
                or grid[r][c] == 0
                or (r, c) in visit
            ):
                return 0

            visit.add((r, c))
            return 1 + dfs(r + 1, c) + dfs(r - 1, c) + dfs(r, c + 1) + dfs(r, c - 1)


        area = 0

        for r in range(ROWS):
            for c in range(COLS):
                area = max(area, dfs(r, c))

        return area


This content originally appeared on DEV Community 👩‍💻👨‍💻 and was authored by SalahElhossiny


Print Share Comment Cite Upload Translate Updates
APA

SalahElhossiny | Sciencx (2022-11-08T06:57:46+00:00) Max Area of Island. Retrieved from https://www.scien.cx/2022/11/08/max-area-of-island/

MLA
" » Max Area of Island." SalahElhossiny | Sciencx - Tuesday November 8, 2022, https://www.scien.cx/2022/11/08/max-area-of-island/
HARVARD
SalahElhossiny | Sciencx Tuesday November 8, 2022 » Max Area of Island., viewed ,<https://www.scien.cx/2022/11/08/max-area-of-island/>
VANCOUVER
SalahElhossiny | Sciencx - » Max Area of Island. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/11/08/max-area-of-island/
CHICAGO
" » Max Area of Island." SalahElhossiny | Sciencx - Accessed . https://www.scien.cx/2022/11/08/max-area-of-island/
IEEE
" » Max Area of Island." SalahElhossiny | Sciencx [Online]. Available: https://www.scien.cx/2022/11/08/max-area-of-island/. [Accessed: ]
rf:citation
» Max Area of Island | SalahElhossiny | Sciencx | https://www.scien.cx/2022/11/08/max-area-of-island/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.