Peaks
Part of the Fundamentals section of Coddy's C journey — lesson 62 of 63.
Challenge
You’re given a 2D grid of integer elevations representing a terrain map. A cell is called a peak if its value is strictly greater than all of its adjacent neighbors (up to 8: north, south, east, west, and the four diagonals).
Rules
- 8 Neighbors: You must check the north, south, east, west, and all four diagonals.
- Boundary Cells: If a cell is on the edge or corner, it has fewer than 8 neighbors. It is still a peak if it is strictly greater than all of its existing neighbors.
- Strictly Greater: If a neighbor has the same elevation as the current cell, the current cell is not a peak.
Input
- Two integers
NandMrepresenting rows and columns. - An
N*Mgrid of integers
Output
- An integer representing the total number of peaks.
- The coordinates (row and column, 0‑indexed) of each peak, sorted first by row then by column.
For example for this input:
5 5
1 2 1 3 4
5 1 1 1 1
1 1 9 1 1
2 1 1 1 2
1 3 1 4 1This is the output:
5
0 4
1 0
2 2
4 1
4 3Explanation The peaks occur at the following locations:
- (0,4) with elevation 4: Greater than neighbors (3, 1, 1).
- (1,0) with elevation 5: Greater than neighbors (1, 2, 1, 1, 1).
- (2,2) with elevation 9: Greater than all 8 surrounding 1s.
- (4,1) with elevation 3: Greater than neighbors (2, 1, 1, 1, 1).
- (4,3) with elevation 4: Greater than neighbors (1, 1, 1, 2, 1).
Try it yourself
#include <stdio.h>
#define MAXN 100
#define MAXM 100
int N, M;
int grid[MAXN][MAXM];
/**
* Returns 1 if the cell at (r, c) is a peak, 0 otherwise.
* A peak must be strictly greater than all existing neighbors.
*/
int is_peak(int r, int c) {
// TODO: Define the relative positions of the 8 neighbors
// (North, South, East, West, and the 4 diagonals).
// TODO: Loop through each neighbor.
// CRITICAL HINT: Before checking grid[nr][nc], you MUST ensure
// that nr and nc are within the bounds (0 to N-1 and 0 to M-1).
return 1; // Placeholder
}
int main() {
// Read dimensions
if (scanf("%d %d", &N, &M) != 2) {
return 1;
}
// TODO: Read the grid values from stdin using nested loops.
// TODO: Iterate over every cell (i, j) in the grid.
// If is_peak(i, j) is true, store the coordinates.
// You can use two arrays like peak_r[MAXN*MAXM] and peak_c[MAXN*MAXM]
// to store the results before printing.
// TODO: Print the total count of peaks.
// TODO: Print each stored (row, col) pair.
// Since you iterate by row then column, they will already be sorted!
return 0;
}All lessons in Fundamentals
3Operators
Arithmetic OperatorsModulo OperatorIncrement/DecrementAssignment OperatorsRelational OperatorsLogical Operators Part 1Logical Operators Part 2Logical Operators Part 3Recap Challenge