Tensorum
YouTubeಕಲಿಯಲು ಪ್ರಾರಂಭಿಸಿ
LeetCode 695 · Graph Fundamentals / DFS-BFS

Max Area of Island

LeetCode 695 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್‌ಥ್ರೂ

DFS returns island size.

ಮಧ್ಯಮArrayDepth-First SearchBreadth-First SearchUnion-FindMatrix
LeetCode ನಲ್ಲಿ ತೆರೆಯಿರಿ ↗

ನಾನು Max Area of Island (LeetCode 695) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — Graph Fundamentals / DFS-BFS ಪ್ಯಾಟರ್ನ್‌ನ ಒಂದು ಮಧ್ಯಮ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.

ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್‌ನಲ್ಲಿದೆ.

Intuition

DFS from each unvisited land cell and let it return the size of the island it explored (1 + sizes from its neighbours). Keep the largest.

Approach

  1. 1

    For each unvisited land cell, area = dfs(cell).

  2. 2

    dfs adds 1 plus the areas returned by unvisited land neighbours.

  3. 3

    Track the maximum.

ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ

DFS areaPythonO(m·n) time
class Solution:
    def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
        di = [0,+1,0,-1] #top,right,bottom,left
        dj = [+1,0,-1,0] #top,right,bottom,left
        m = len(grid)
        n = len(grid[0])
        visited = set()
        def dfs(row,col):
            visited.add((row,col))
            max_area = 1
            for k in range(4):
                nrow = row+di[k]
                ncol = col+dj[k]
                if 0<=nrow<m and 0<=ncol<n and grid[nrow][ncol]==1 and (nrow,ncol) not in visited:
                    max_area+=dfs(nrow,ncol) 
            return max_area

        max_area = 0
        for row in range(m):
            for col in range(n):
                if grid[row][col]==1 and (row,col) not in visited:
                    max_area=max(max_area,dfs(row,col))
        return max_area
ಸ್ಟೆಪ್-ಥ್ರೂ ಲೋಡ್ ಆಗುತ್ತಿದೆ…

Max Area of Island — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು

Max Area of Island ಹಿಂದಿನ intuition ಏನು?

DFS from each unvisited land cell and let it return the size of the island it explored (1 + sizes from its neighbours). Keep the largest.

Max Area of Island (LeetCode 695) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?

1. For each unvisited land cell, area = dfs(cell). 2. dfs adds 1 plus the areas returned by unvisited land neighbours. 3. Track the maximum.

Max Area of Island ನ time ಮತ್ತು space complexity ಎಷ್ಟು?

Time: O(m · n). Space: O(m · n). (Accepted approach: DFS area.)

Max Area of Island ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?

No land → 0.