Skip to main content
  1. Posts/

LeetCode-1765 地图中的最高点

·1 min·

LeetCode-1765 地图中的最高点 #

Solution 1 #

多源 BFS.

代码如下:

class Solution:
    def highestPeak(self, isWater: List[List[int]]) -> List[List[int]]:
        m, n = len(isWater), len(isWater[0])
        q, h = [], 0
        ans = [[-1 for _ in range(n)] for _ in range(m)]
        vis = [[0 for _ in range(n)] for _ in range(m)]
        for i in range(m):
            for j in range(n):
                if isWater[i][j] == 1:
                    q.append((i, j))
                    vis[i][j] = 1

        while q:
            nxt_q = []
            while q:
                x, y = q.pop()
                if ans[x][y] == -1:
                    ans[x][y] = h
                for dx, dy in [[0, 1], [0, -1], [1, 0], [-1, 0]]:
                    nx, ny = x + dx, y + dy
                    if 0 <= nx < m and 0 <= ny < n and ans[nx][ny] == -1 and vis[nx][ny] == 0: 
                        nxt_q.append((nx, ny))
                        vis[nx][ny] = 1
            q = nxt_q.copy()
            h += 1
        return ans