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.