Given a 2D matrix of integers, find and return any "peak" element within the matrix. A peak element is an element in the matrix that is greater than or equal to all of its adjacent neighbors. Adjacent neighbors are the elements directly to its left, right, top, and bottom. For elements at the edges or corners of the matrix, missing neighbors are considered to have a value of negative infinity.
Examines each number in the matrix and checks if it's larger than all its immediate neighbors (above, below, left, and right). If it is, that number is considered a peak.
matrix = [ [ 1, 2, 3 ], [ 4, 9, 6 ], [ 7, 8, 5 ] ] output = [] h = len(matrix) w = len(matrix[0]) for i in range(h): for j in range(w): t = float('-inf') if i - 1 < 0 else matrix[i - 1][j] l = float('-inf') if j - 1 < 0 else matrix[i][j - 1] b = float('-inf') if i + 1 >= h else matrix[i + 1][j] r = float('-inf') if j + 1 >= w else matrix[i][j + 1] c = matrix[i][j] if c > t and c > l and c > b and c > r: output.append([i, j]) print(output)
const matrix = [ [ 1, 2, 3 ], [ 4, 9, 6 ], [ 7, 8, 5 ] ]; const output = []; const h = matrix.length; const w = matrix[0].length; for (let i = 0; i < h; i++) { for (let j = 0; j < w; j++) { let t = (i-1 < 0) ? -Infinity : matrix[i - 1][j]; let l = (j-1 < 0) ? -Infinity : matrix[i][j - 1]; let b = (i+1 >= h) ? -Infinity : matrix[i + 1][j]; let r = (j+1 >= w) ? -Infinity : matrix[i][j + 1]; let c = matrix[i][j]; if (c > t && c > l && c > b && c > r) { output.push([i, j]); } } } console.log(output);