Tensorum
YouTubeशिकायला सुरुवात करा
LeetCode 1765 · Multi-Source BFS

Map of Highest Peak

LeetCode 1765 · मध्यम · उपाय, intuition आणि टप्प्याटप्प्याने वॉकथ्रू

Height = BFS distance from water.

मध्यमArrayBreadth-First SearchMatrix

मी 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.