You are given a 2D grid grid
of size n x m
with the following conditions:
grid[i][j]
is an integer representing the height at cell (i, j)
.A peak in the grid is an element that is greater than its 4 neighboring cells (top, bottom, left, and right). We need to find and return a list of all peak elements in the grid.
n
and m
?
n
and m
are both at least 1.(i, j)
, we compare it with its neighbors (i-1, j)
, (i+1, j)
, (i, j-1)
, and (i, j+1)
if they exist.k
is the number of peak elements.#include <vector>
std::vector<int> findPeaks(std::vector<std::vector<int>>& grid) {
if (grid.empty()) return {};
int n = grid.size();
int m = grid[0].size();
std::vector<int> peaks;
// Directions for traversing: up, down, left, right
std::vector<std::pair<int, int>> directions = \{\{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
bool isPeak = true;
for (const auto& dir : directions) {
int ni = i + dir.first;
int nj = j + dir.second;
// Check if neighbor is in the grid
if (ni >= 0 && ni < n && nj >= 0 && nj < m) {
if (grid[i][j] <= grid[ni][nj]) {
isPeak = false;
break;
}
}
}
if (isPeak) {
peaks.push_back(grid[i][j]);
}
}
}
return peaks;
}
peaks
vector.peaks
vector containing all peak elements.This code ensures that we handle boundary conditions appropriately and only compare existing neighboring elements.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?