#1765

Map of Highest Peak

Medium
ArrayBreadth-First SearchMatrixBreadth-First SearchMatrix Traversal
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(m * n)
Space
O(1)
O(m * n)
💡

Intuition

Time O(m * n)Space O(m * n)

The optimal solution uses a multi-source Breadth-First Search (BFS) starting from all water cells. This efficiently propagates height values to land cells while ensuring the height difference condition is satisfied.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a height matrix and a queue for BFS, adding all water cells with height 0.
  2. 2Step 2: While the queue is not empty, pop a cell and check its adjacent cells.
  3. 3Step 3: For each adjacent land cell, set its height to the current cell's height + 1 if it's not already set, and add it to the queue.
solution.py20 lines
1from collections import deque
2
3def highestPeak(isWater):
4    m, n = len(isWater), len(isWater[0])
5    height = [[-1] * n for _ in range(m)]
6    queue = deque()
7    for i in range(m):
8        for j in range(n):
9            if isWater[i][j] == 1:
10                height[i][j] = 0
11                queue.append((i, j))
12    directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
13    while queue:
14        x, y = queue.popleft()
15        for dx, dy in directions:
16            nx, ny = x + dx, y + dy
17            if 0 <= nx < m and 0 <= ny < n and height[nx][ny] == -1:
18                height[nx][ny] = height[x][y] + 1
19                queue.append((nx, ny))
20    return height

Complexity note: The time complexity is O(m * n) because we visit each cell once during the BFS. The space complexity is O(m * n) due to the height matrix and the queue used for BFS.

  • 1The height of each land cell is determined by its proximity to water cells.
  • 2Using BFS allows for efficient propagation of height values while maintaining the height difference constraint.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.