๐ WAYPOINT LESSON
The Q4 shapes
โญโญ intermediateโณ 12 min read๐ Lesson 145 of 256
Position reports, conditional transforms, neighborhood counts.
Q4: one method, one grid, nine points. The recurring shapes:
Find-and-report-position โ "return {row, col} of the largest value" as an int[]:
public int[] findMax(int[][] grid) {
int[] at = new int[2];
for (int r = 0; r < grid.length; r++) {
for (int c = 0; c < grid[r].length; c++) {
if (grid[r][c] > grid[at[0]][at[1]]) {
at[0] = r;
at[1] = c;
}
}
}
return at;
}
Seed from (0,0) โ the precondition grid.length >= 1 makes it legal โ
and keep a strict > for the earliest tie.
Conditional transform โ mutate cells matching a rule:
for (int r = 0; r < grid.length; r++) {
for (int c = 0; c < grid[r].length; c++) {
if (grid[r][c] < 0) {
grid[r][c] = 0;
}
}
}
Count by neighborhood โ the guarded-neighbor pattern (Module 8) inside a full-grid loop.
The Q4-specific discipline: when the answer is a POSITION, decide immediately how to encode it (int[2]? an int code like 10*r+c? a row-only?) โ the prompt's return type forces one; misreading it is the classic zero.