Similar Problems
Similar Problems not available
Map Of Highest Peak - Leetcode Solution
Companies:
LeetCode: Map Of Highest Peak Leetcode Solution
Difficulty: Medium
Topics: matrix array breadth-first-search
Problem Statement:
Given a list of mountain ranges represented by a 2D array of integers, where each integer represents the height of a peak in the range, return a matrix of the same dimensions where each element represents the height of the highest peak in its 3x3 neighborhood.
Solution:
There are different approaches to solving this problem, but the basic idea is to iterate over the entire input matrix and, for each cell, find the maximum value in its neighborhood. Here is one possible solution:
-
Initialize an output matrix of the same dimensions as the input matrix, with all elements set to zero.
-
Iterate over the rows and columns of the input matrix. For each cell, do the following:
a. Define the min/max row and column indices of the 3x3 neighborhood around the current cell. For example, if the current cell is at row i and column j, the neighborhood indices would be from i-1 to i+1 for the rows, and from j-1 to j+1 for the columns.
b. Check if the neighborhood indices are within the bounds of the input matrix. If not, skip to the next cell.
c. Find the maximum value in the neighborhood by iterating over the neighborhood indices and comparing the corresponding values in the input matrix.
d. Update the output matrix with the maximum value found in step c, at the same row and column indices as the current cell.
-
Return the output matrix.
Here is the Python implementation of this solution:
def highest_peaks(mountain_ranges):
rows, cols = len(mountain_ranges), len(mountain_ranges[0])
output = [[0]*cols for _ in range(rows)]
for i in range(rows):
for j in range(cols):
max_val = 0
for r in range(max(0, i-1), min(rows, i+2)):
for c in range(max(0, j-1), min(cols, j+2)):
if mountain_ranges[r][c] > max_val:
max_val = mountain_ranges[r][c]
output[i][j] = max_val
return output
This solution has a time complexity of O(rowscols9) or O(rowscols), since we are iterating over each cell and its entire 3x3 neighborhood. The space complexity is also O(rowscols), since we are creating an output matrix of the same dimensions as the input matrix.
Map Of Highest Peak Solution Code
1