Tensorum
YouTubeகற்கத் தொடங்குங்கள்
LeetCode 1765 · Multi-Source BFS

Map of Highest Peak

LeetCode 1765 · நடுத்தரம் · தீர்வு, intuition & படிப்படியான வாக்த்ரூ

Height = BFS distance from water.

நடுத்தரம்ArrayBreadth-First SearchMatrix
LeetCode இல் திற ↗

நான் Map of Highest Peak (LeetCode 1765) ஐ இப்படித் தீர்த்தேன் — Multi-Source BFS பேட்டர்னின் ஒரு நடுத்தரம் பிராப்ளம். கீழே: intuition, படிப்படியான approach, என் accepted Python கோட், animated test cases மற்றும் line-by-line debugger.

கீழேயுள்ள விளக்கம் ஆங்கிலத்தில் உள்ளது.

Intuition

Water cells are height 0 and neighbours may differ by at most 1, so the highest possible height of a cell is its distance to the nearest water. That's a multi-source BFS from all water cells.

Approach

  1. 1

    Queue every water cell.

  2. 2

    BFS: neighbour height = current + 1 on first visit.

  3. 3

    Return the height grid.

நான் எப்படித் தீர்த்தேன்

Multi-source BFSPythonO(m·n) time
class Solution:
    def highestPeak(self, isWater: list[list[int]]) -> list[list[int]]:
        q = deque([])
        m = len(isWater)
        n = len(isWater[0])
        visited = set()
        dist = [[0]*n for _ in range(m)]
        for i in range(m):
            for j in range(n):
                if isWater[i][j]==1: #will start from water cell
                    q.append((i,j))
                    visited.add((i,j))
        di =[0,+1,0,-1]
        dj=[+1,0,-1,0]
        while q:
            x0,y0 = q.popleft()
            for k in range(4):
                x1 = x0+di[k]
                y1 = y0+dj[k]
                if 0<=x1<m and 0<=y1<n and (x1,y1) not in visited:
                    dist[x1][y1]=1+dist[x0][y0]
                    visited.add((x1,y1))
                    q.append((x1,y1))
        return dist
ஸ்டெப்-த்ரூ ஏற்றுகிறது…

Map of Highest Peak — அடிக்கடி கேட்கப்படும் கேள்விகள்

Map of Highest Peak பின்னாலுள்ள intuition என்ன?

Water cells are height 0 and neighbours may differ by at most 1, so the highest possible height of a cell is its distance to the nearest water. That's a multi-source BFS from all water cells.

Map of Highest Peak (LeetCode 1765) ஐ எப்படித் தீர்ப்பது?

1. Queue every water cell. 2. BFS: neighbour height = current + 1 on first visit. 3. Return the height grid.

Map of Highest Peak இன் time மற்றும் space complexity என்ன?

Time: O(m · n). Space: O(m · n). (Accepted approach: Multi-source BFS.)

Map of Highest Peak இல் பொதுவான தவறுகள் என்ன?

Water cells must stay 0.