2D Arrays - Complete Interactive Lesson
Part 1: Core Concepts
🔢 2D Array Algorithms
Part 1 of 7 — Row/Column Processing, Searching, and Modifying
Processing Individual Rows or Columns
Sum of a Specific Row
public int rowSum(int[][] matrix, int row) {
int sum = 0;
for (int c = 0; c < matrix[row].length; c++) {
sum += matrix[row][c];
}
return sum;
}
Sum of a Specific Column
public int colSum(int[][] matrix, int col) {
int sum = 0;
for (int r = 0; r < matrix.length; r++) {
sum += matrix[r][col];
}
return sum;
}
🔑 Row processing fixes the row index and loops over columns. Column processing fixes the column index and loops over rows.
Finding a Value in a 2D Array
public boolean contains(int[][] matrix, int target) {
for (int r = 0; r < matrix.length; r++) {
for (int c = 0; c < matrix[r].length; c++) {
if (matrix[r][c] == target) {
return true;
}
}
}
return false;
}
| Algorithm | Approach |
|---|---|
| Row sum/avg | Fix row, loop columns |
| Column sum/avg | Fix column, loop rows |
| Search | Nested loops, return true if found |
| Count matches | Nested loops, increment counter |
| Find max/min | Initialize with [0][0], compare all |
Concept Check 🎯
Modifying 2D Array Elements
Multiply All Elements by 2
for (int r = 0; r < matrix.length; r++) {
for (int c = 0; c < matrix[r].length; c++) {
matrix[r][c] *= 2;
}
}
Replace Negatives with Zero
for (int r = 0; r < matrix.length; r++) {
for (int c = 0; c < matrix[r].length; c++) {
if (matrix[r][c] < 0) {
matrix[r][c] = 0;
}
}
}
Diagonal Elements
// Main diagonal (row == col): top-left to bottom-right
// Only works for square matrices!
for (int i = 0; i < matrix.length; i++) {
System.out.println(matrix[i][i]);
}
Edge Elements (Border)
// An element is on the edge if:
// r == 0 (first row), r == rows-1 (last row),
// c == 0 (first col), c == cols-1 (last col)
for (int r = 0; r < matrix.length; r++) {
for (int c = 0; c < matrix[r].length; c++) {
if (r == 0 || r == matrix.length - 1 ||
c == 0 || c == matrix[r].length - 1) {
// This element is on the border
}
}
}
Applied Recall ✍️
-
To process a single row, fix the _______ index and loop over columns.
-
Diagonal elements in a square matrix satisfy the condition row == _______.
-
An element is on the border of a 2D array if its row or column index equals 0 or the _______ valid index.
2D Array Algorithms 🔍
AP Exam Strategy: 2D Array Algorithms
- Row processing = fix row, vary column. Column processing = fix column, vary row
- Use
matrix.lengthfor the number of rows andmatrix[0].lengthfor the number of columns; every 2D array on the AP exam is rectangular, so each row has the same length - Searching a 2D array is just nested linear search
- Know how to find: sum, average, max, min for the whole array, a specific row, or a specific column
- Diagonal, border, and neighbor-checking are common FRQ patterns
- When modifying elements, use standard for loops (not enhanced for)
AP-Style Application 🎯
Part 2: Whole-Grid Algorithms: Totals, Extremes, Counts, and Searches
🔢 2D Array Algorithms
Part 2 of 7 — Whole-Grid Algorithms: Totals, Extremes, Counts, and Searches
Part 1 worked on one row or one column at a time. This part runs the standard algorithms over every element of a 2D array (CED Topic 4.13). Each one is a 1D algorithm you already know, wrapped in a row-major nested loop.
| Algorithm | Answers the question | Result |
|---|---|---|
| Total and average | What is the sum of every element? The mean? | int, then double |
| Maximum or minimum with location | What is the extreme value, and in which row and column? | two indices |
| Count | How many elements meet a condition? | int |
| At least one / all | Does any element qualify? Does every element? | boolean |
| Search for a location | Where is the first copy of a target? | an int array {r, c} |
All examples use this 3 x 4 grid of daily sales (rows are weeks, columns are store locations):
int[][] sales = {
{12, 7, 19, 4},
{ 9, 21, 3, 15},
{18, 6, 21, 15}
};
🔑 Key Concept: In a rectangular grid,
grid.lengthis the number of rows andgrid[0].lengthis the number of columns. The number of elements isgrid.length * grid[0].length, here 3 x 4 = 12, and a full traversal visits each one exactly once.
Total and Average
int total = 0;
for (int r = 0; r < sales.length; r++) {
for (int c = 0; c < sales[0].length; c++) {
total += sales[r][c];
}
}
double avg = (double) total / (sales.length * sales[0].length);
total is declared before both loops, so it keeps growing across rows: the row sums 42, 48 and 60 add to 150. The divisor is the element count, 12.
| Expression | Value | Why |
|---|---|---|
(double) total / (sales.length * sales[0].length) | 12.5 | the cast makes the division a double division |
total / (sales.length * sales[0].length) | 12 | int / int drops the .5, even if stored in a double (12.0) |
(double) total / sales.length | 50.0 | divides by the number of rows, which is the average row sum |
Maximum and Minimum With Their Location
To report where the extreme value is, keep both indices and compare against the element they point to:
int maxRow = 0;
int maxCol = 0;
for (int r = 0; r < sales.length; r++) {
for (int c = 0; c < sales[0].length; c++) {
if (sales[r][c] > sales[maxRow][maxCol]) {
maxRow = r;
maxCol = c;
}
}
}
// maxRow is 1, maxCol is 1, and sales[maxRow][maxCol] is 21
- Starting at
[0][0]makes the first element the first candidate, so the method works for any grid, including one whose values are all negative. - Starting a separate
int max = 0;fails for an all-negative grid: nothing is greater than 0, so the answer is 0, which is not in the grid. - Changing
>to<finds the minimum: 3, at row 1, column 2.
Ties in Row-Major Order
The value 21 appears at row 1, column 1 and at row 2, column 2. A row-major traversal meets row 1 first.
| Test | Result | Reason |
|---|---|---|
> | row 1, column 1 | a later 21 only ties, so the location stays |
>= | row 2, column 2 | every later 21 replaces the location, so the last one wins |
Counting
int count = 0;
for (int r = 0; r < sales.length; r++) {
for (int c = 0; c < sales[0].length; c++) {
if (sales[r][c] > 10) {
count++;
}
}
}
// count is 7: 12, 19, 21, 15, 18, 21, 15
🎯 AP Connection: Question 4 of the free-response section usually asks for an index, a count, or a changed grid, not for a printed value. If the prompt asks for a location, keep the row and the column; returning only the value earns nothing for that step.
Concept Check 🎯
Segment A
int[][] g = {{4, 9, 2}, {7, 1, 4}};
int total = 0;
for (int r = 0; r < g.length; r++) {
for (int c = 0; c < g[0].length; c++) {
total += g[r][c];
}
}
double avg = total / (g.length * g[0].length);
System.out.println(avg);
Segment B
int[][] t = {{-6, -2}, {-9, -4}};
int max = 0;
for (int r = 0; r < t.length; r++) {
for (int c = 0; c < t[0].length; c++) {
if (t[r][c] > max) {
max = t[r][c];
}
}
}
Segment C
int[][] p = {{5, 8, 3}, {8, 2, 8}};
int bestR = 0;
int bestC = 0;
for (int r = 0; r < p.length; r++) {
for (int c = 0; c < p[0].length; c++) {
if (p[r][c] >= p[bestR][bestC]) {
bestR = r;
bestC = c;
}
}
}
At Least One vs. All
The 1D patterns carry over. The deciding return goes inside the inner loop, and the default return goes after both loops.
public static boolean anyZero(int[][] grid) {
for (int r = 0; r < grid.length; r++) {
for (int c = 0; c < grid[0].length; c++) {
if (grid[r][c] == 0) {
return true; // one example proves it
}
}
}
return false; // only after every element
}
public static boolean allInRange(int[][] grid, int low, int high) {
for (int r = 0; r < grid.length; r++) {
for (int c = 0; c < grid[0].length; c++) {
if (grid[r][c] < low || grid[r][c] > high) {
return false; // one counterexample disproves it
}
}
}
return true;
}
For sales, anyZero returns false, allInRange(sales, 1, 25) returns true, and allInRange(sales, 5, 25) returns false as soon as it reaches the 4.
The 2D Bug: A Default Return Between the Loops
for (int r = 0; r < grid.length; r++) {
for (int c = 0; c < grid[0].length; c++) {
if (grid[r][c] == 0) {
return true;
}
}
return false; // runs as soon as row 0 is finished
}
The return false is inside the outer loop, so the method gives up after row 0. For {{4, 1}, {0, 6}} it returns false even though row 1 holds a 0.
Searching for a Location
Part 1's search returned only true or false. To report where a target is, return the two indices in a new int array, and use {-1, -1} (not a real location) when the target is missing.
public static int[] findValue(int[][] grid, int target) {
for (int r = 0; r < grid.length; r++) {
for (int c = 0; c < grid[0].length; c++) {
if (grid[r][c] == target) {
return new int[] {r, c};
}
}
}
return new int[] {-1, -1};
}
| Call | Returns | Elements examined |
|---|---|---|
findValue(sales, 21) | {1, 1} | 6 |
findValue(sales, 3) | {1, 2} | 7 |
findValue(sales, 50) | {-1, -1} | 12, every element |
The method finds the first copy in row-major order. A column-major version (columns in the outer loop) finds the first copy in column-major order, which can be a different element.
Pick the Pattern 🔍
Worked Example: How Many Values Reach the Average?
Task. Return the number of elements that are greater than or equal to the average of all elements in grid.
public static int countAtLeastAverage(int[][] grid) {
int total = 0;
for (int r = 0; r < grid.length; r++) {
for (int c = 0; c < grid[0].length; c++) {
total += grid[r][c];
}
}
double avg = (double) total / (grid.length * grid[0].length);
int count = 0;
for (int r = 0; r < grid.length; r++) {
for (int c = 0; c < grid[0].length; c++) {
if (grid[r][c] >= avg) {
count++;
}
}
}
return count;
}
Step 1 — Why two passes? The average is not known until every element has been added, so a single traversal cannot compare elements with it. The first pass totals; the second pass counts.
Step 2 — First pass on sales. The total is 150, there are 12 elements, and avg is 12.5.
Step 3 — Second pass. Compare each element with 12.5:
| Row | Elements | At least 12.5 |
|---|---|---|
| 0 | 12, 7, 19, 4 | 19 |
| 1 | 9, 21, 3, 15 | 21, 15 |
| 2 | 18, 6, 21, 15 | 18, 21, 15 |
Step 4 — Answer. The method returns 6.
Step 5 — The int-division trap. Without the cast, total / 12 is 12, and the comparison 12 >= 12 is true, so the element 12 is counted too and the method returns 7. The bug is invisible on grids whose total happens to divide evenly, which is why it survives casual testing.
AP-Style Application 🎯
Segment A
int[][] pts = {
{6, 3, 8},
{3, 9, 3},
{7, 3, 5}
};
Method B
public static boolean anyNegative(int[][] grid) {
for (int r = 0; r < grid.length; r++) {
for (int c = 0; c < grid[0].length; c++) {
if (grid[r][c] < 0) {
return true;
}
}
return false;
}
return false;
}
Part 3: Row and Column Results
🔢 2D Array Algorithms
Part 3 of 7 — Row and Column Results
Part 1 found the sum of one row or one column. Many free-response tasks need an answer for every row or every column: each student's total, each day's high, the column that is all the same. This part builds those results (CED Topic 4.13) and then changes rows and columns in place.
| In this part |
|---|
| A results array with one slot per row, or one slot per column |
| The row with the largest sum |
| Row and column checks: increasing, all equal |
| Swapping two columns or two rows; reversing every row |
| Comparing each element with the one above it |
| Worked example: a gradebook report |
Most examples use this gradebook (rows are students, columns are quizzes):
int[][] scores = {
{82, 90, 75},
{68, 74, 80},
{95, 88, 91},
{70, 85, 64}
};
🔑 Key Concept: Whatever the outer loop walks over is what you get one answer for. For one answer per row, loop over rows on the outside; for one answer per column, loop over columns on the outside.
One Result per Row
public static int[] rowTotals(int[][] grid) {
int[] totals = new int[grid.length]; // one slot per row
for (int r = 0; r < grid.length; r++) {
for (int c = 0; c < grid[0].length; c++) {
totals[r] += grid[r][c];
}
}
return totals;
}
rowTotals(scores) returns {247, 222, 274, 219}. The new array starts full of 0s, so totals[r] += needs no separate reset.
One Result per Column
public static int[] colTotals(int[][] grid) {
int[] totals = new int[grid[0].length]; // one slot per column
for (int c = 0; c < grid[0].length; c++) {
for (int r = 0; r < grid.length; r++) {
totals[c] += grid[r][c];
}
}
return totals;
}
colTotals(scores) returns {315, 337, 310}.
| Results array sized with | Holds | Mistake to avoid |
|---|---|---|
new int[grid.length] | one value per row | using it for columns: extra 0 slots when there are more rows than columns, and an ArrayIndexOutOfBoundsException when there are fewer |
new int[grid[0].length] | one value per column | using it for rows, with the same two failures reversed |
On scores (4 rows, 3 columns), sizing the column totals with grid.length gives {315, 337, 310, 0}: no crash, but a fake fourth column.
The Row With the Largest Sum
public static int bestRow(int[][] grid) {
int best = 0;
int bestSum = 0;
for (int r = 0; r < grid.length; r++) {
int sum = 0; // reset for every row
for (int c = 0; c < grid[0].length; c++) {
sum += grid[r][c];
}
if (r == 0 || sum > bestSum) {
best = r;
bestSum = sum;
}
}
return best;
}
The test r == 0 makes row 0 the first candidate, the 2D version of starting a maximum at the first element. bestRow(scores) returns 2, the row whose sum is 274.
The misplaced declaration. If int sum = 0; moves above the outer loop, sum is never reset. It holds running totals 247, 469, 743, 962, so with positive values the last row always looks best and the method returns 3.
Concept Check 🎯
Segment A
int[][] q = {{3, 8, 1}, {6, 2, 7}};
int[] result = colTotals(q);
Segment B
int[][] w = {{9, 9}, {1, 2}, {3, 1}};
int best = 0;
int bestSum = 0;
int sum = 0;
for (int r = 0; r < w.length; r++) {
for (int c = 0; c < w[0].length; c++) {
sum += w[r][c];
}
if (r == 0 || sum > bestSum) {
best = r;
bestSum = sum;
}
}
Checking a Row or a Column
A row or column check is the "all" pattern from Part 2 applied to one line of the grid.
// true if row r is strictly increasing from left to right
public static boolean isRowIncreasing(int[][] grid, int r) {
for (int c = 0; c < grid[0].length - 1; c++) {
if (grid[r][c] >= grid[r][c + 1]) {
return false;
}
}
return true;
}
// true if every element in column c equals the top element
public static boolean isColumnSame(int[][] grid, int c) {
for (int r = 1; r < grid.length; r++) {
if (grid[r][c] != grid[0][c]) {
return false;
}
}
return true;
}
isRowIncreasing(scores, 1) is true (68, 74, 80); rows 0, 2 and 3 return false. The bound grid[0].length - 1 keeps c + 1 inside the row.
Swapping Two Columns vs. Two Rows
public static void swapColumns(int[][] grid, int a, int b) {
for (int r = 0; r < grid.length; r++) { // one swap in every row
int temp = grid[r][a];
grid[r][a] = grid[r][b];
grid[r][b] = temp;
}
}
A row is stored as its own 1D array, so two rows can be swapped by swapping the references: int[] temp = grid[a]; grid[a] = grid[b]; grid[b] = temp;. A column is not stored anywhere as an array; it is one element from each row, so swapping columns always needs the loop.
Reversing Every Row in Place
int n = grid[0].length;
for (int r = 0; r < grid.length; r++) {
for (int c = 0; c < n / 2; c++) {
int temp = grid[r][c];
grid[r][c] = grid[r][n - 1 - c];
grid[r][n - 1 - c] = temp;
}
}
| Inner bound | Result for {{1, 2, 3, 4}, {5, 6, 7, 8}} |
|---|---|
c < n / 2 | {{4, 3, 2, 1}, {8, 7, 6, 5}} |
c < n | unchanged: every pair is swapped twice |
With an odd number of columns, n / 2 skips the middle element, which is already in place. Reversing a column is the same idea with r and grid.length / 2.
Comparing Each Element With the One Above It
int count = 0;
for (int r = 1; r < grid.length; r++) { // row 0 has nothing above it
for (int c = 0; c < grid[0].length; c++) {
if (grid[r][c] > grid[r - 1][c]) {
count++;
}
}
}
For scores the count is 4: one quiz rises from row 0 to row 1 (75 to 80), and all three rise from row 1 to row 2. Starting r at 0 reads grid[-1] and throws an ArrayIndexOutOfBoundsException.
Pick the Bound 🔍
Worked Example: A Gradebook Report
Task. For scores, find each student's total, the best student, each quiz's average as a double, and the hardest quiz (the lowest average).
Step 1 — Student totals (one per row). rowTotals(scores) gives {247, 222, 274, 219}.
Step 2 — Best student. The largest total is 274, so bestRow(scores) returns 2.
Step 3 — Quiz averages (one per column).
int[] colSums = colTotals(scores);
double[] quizAvg = new double[colSums.length];
for (int c = 0; c < colSums.length; c++) {
quizAvg[c] = (double) colSums[c] / scores.length; // divide by the number of students
}
| Quiz (column) | Column total | Average |
|---|---|---|
| 0 | 315 | 78.75 |
| 1 | 337 | 84.25 |
| 2 | 310 | 77.5 |
The divisor is scores.length, the number of rows, because each column has one value per student. Without the cast the averages become 78.0, 84.0 and 77.0.
Step 4 — Hardest quiz. Run a minimum-index search over quizAvg: the lowest value, 77.5, is at index 2.
Step 5 — Check the shapes. Student results have length 4 (scores.length); quiz results have length 3 (scores[0].length). Mixing them up is the most common error in this kind of report.
Applied Recall ✍️
int[][] g = {
{5, 2, 8, 1},
{3, 9, 4, 6},
{7, 1, 2, 9}
};
-
What value is at index 3 of the array returned by
colTotals(g)? _______ -
What does
bestRow(g)return? _______ -
How many elements of g are greater than the element directly above them? _______
Part 4: Neighbors, Diagonals, and Regions
🔢 2D Array Algorithms
Part 4 of 7 — Neighbors, Diagonals, and Regions
Game boards, images and maps all ask questions about an element and the elements around it. This part covers neighbor checks, the second diagonal, interior regions, 2 x 2 blocks and symmetry (CED Topic 4.13). Every one of them comes down to the same skill: computing an index and proving it stays inside the grid.
| Region | Index pattern | Guard needed |
|---|---|---|
| 4 neighbors (up, down, left, right) | [r - 1][c], [r + 1][c], [r][c - 1], [r][c + 1] | one test per direction |
| 8 neighbors | [r + dr][c + dc] for dr and dc from -1 to 1 | a range test, and skip the element itself |
| Anti-diagonal of an n x n grid | [i][n - 1 - i] | none when i runs 0 to n - 1 |
| Interior elements | r from 1 to length - 2 | none: every interior element has all 4 neighbors |
| 2 x 2 blocks | top-left corner [r][c] | r stops at length - 2, c at [0].length - 2 |
Most examples use this 3 x 4 height map:
int[][] h = {
{3, 5, 2, 4},
{6, 9, 1, 7},
{2, 8, 4, 3}
};
🔑 Key Concept: Before you read
grid[r - 1][c], prove thatr - 1is at least 0. Before you readgrid[r + 1][c], prove thatr + 1is at mostgrid.length - 1. Java checks every index at run time and stops the program with an ArrayIndexOutOfBoundsException when the proof is missing.
The Four Neighbors
public static int neighborSum(int[][] grid, int r, int c) {
int sum = 0;
if (r > 0) {
sum += grid[r - 1][c]; // up
}
if (r < grid.length - 1) {
sum += grid[r + 1][c]; // down
}
if (c > 0) {
sum += grid[r][c - 1]; // left
}
if (c < grid[0].length - 1) {
sum += grid[r][c + 1]; // right
}
return sum;
}
| Call | Neighbors that exist | Returns |
|---|---|---|
neighborSum(h, 1, 1) | up 5, down 8, left 6, right 1 | 20 |
neighborSum(h, 0, 0) | down 6, right 5 | 11 |
neighborSum(h, 0, 2) | down 1, left 5, right 4 | 10 |
A corner element has 2 neighbors, an edge element that is not a corner has 3, and an interior element has 4.
Guard Order Matters
Java evaluates && left to right and stops at the first false, so the bounds test must come first:
| Condition at r = 0 | Result |
|---|---|
r > 0 && grid[r - 1][c] > 5 | false; the array is never read |
grid[r - 1][c] > 5 && r > 0 | ArrayIndexOutOfBoundsException: index -1 is read first |
The Eight Neighbors
Two small loops over the offsets -1, 0 and 1 reach all eight surrounding elements:
public static int countBig(int[][] grid, int r, int c, int limit) {
int count = 0;
for (int dr = -1; dr <= 1; dr++) {
for (int dc = -1; dc <= 1; dc++) {
int nr = r + dr;
int nc = c + dc;
if ((dr != 0 || dc != 0) && nr >= 0 && nr < grid.length
&& nc >= 0 && nc < grid[0].length) {
if (grid[nr][nc] > limit) {
count++;
}
}
}
}
return count;
}
(dr != 0 || dc != 0)skips the offset (0, 0), which is the element itself.countBig(h, 1, 2, 5)returns 3: of the eight neighbors of the 1, the values 9, 7 and 8 exceed 5.countBig(h, 0, 0, 5)returns 2: the corner has only three neighbors (5, 6 and 9).- Without the skip test,
countBig(h, 1, 1, 5)counts the 9 itself and returns 3 instead of 2.
Concept Check 🎯
int[][] m = {
{4, 1, 6},
{2, 8, 3},
{5, 7, 9},
{1, 0, 2}
};
The Anti-Diagonal
Part 1 used grid[i][i] for the main diagonal (top-left to bottom-right) of a square grid. The anti-diagonal runs from top-right to bottom-left: in row i, the column is n - 1 - i.
int[][] sq = {
{2, 7, 1, 5},
{4, 3, 8, 6},
{9, 0, 6, 2},
{1, 5, 4, 7}
};
int n = sq.length;
int anti = 0;
for (int i = 0; i < n; i++) {
anti += sq[i][n - 1 - i]; // 5 + 8 + 0 + 1
}
// anti is 14; the main diagonal (2 + 3 + 6 + 7) is 18
Writing sq[i][n - i] reads sq[0][4] on the first pass and throws. To test whether an element is on either diagonal, use r == c || r + c == n - 1: a 4 x 4 grid has 8 such elements, and a 5 x 5 grid has 9, because the center belongs to both.
Interior Elements
Shrinking both loops by one at each end leaves only elements that have all four neighbors, so the body needs no guards:
for (int r = 1; r < grid.length - 1; r++) {
for (int c = 1; c < grid[0].length - 1; c++) {
// grid[r - 1][c], grid[r + 1][c], grid[r][c - 1], grid[r][c + 1] are all safe
}
}
h has (3 - 2) x (4 - 2) = 2 interior elements: the 9 and the 1 in row 1. A 5 x 6 grid has 3 x 4 = 12.
2 x 2 Blocks
Each block is named by its top-left corner, so the corner must leave room for one more row and one more column:
int bestSum = 0;
int bestR = 0;
int bestC = 0;
for (int r = 0; r < grid.length - 1; r++) {
for (int c = 0; c < grid[0].length - 1; c++) {
int s = grid[r][c] + grid[r][c + 1] + grid[r + 1][c] + grid[r + 1][c + 1];
if ((r == 0 && c == 0) || s > bestSum) {
bestSum = s;
bestR = r;
bestC = c;
}
}
}
| Top-left corner | (0, 0) | (0, 1) | (0, 2) | (1, 0) | (1, 1) | (1, 2) |
|---|---|---|---|---|---|---|
Block sum in h | 23 | 17 | 14 | 25 | 22 | 15 |
A 3 x 4 grid has (3 - 1) x (4 - 1) = 6 blocks, and the best is the block whose corner is row 1, column 0. With c < grid[0].length, the last corner in each row reads column 4 and throws.
Symmetry
A square grid is symmetric when grid[r][c] == grid[c][r] for every r and c. Comparing only the elements above the diagonal checks each pair once:
public static boolean isSymmetric(int[][] grid) {
for (int r = 0; r < grid.length; r++) {
for (int c = r + 1; c < grid.length; c++) {
if (grid[r][c] != grid[c][r]) {
return false;
}
}
}
return true;
}
{{1, 4, 7}, {4, 2, 5}, {7, 5, 3}} is symmetric after 3 comparisons. A 4 x 4 grid needs 3 + 2 + 1 = 6 comparisons, and a 5 x 5 grid needs 10.
Pick the Index 🔍
Worked Example: Counting Peaks
Task. An element is a peak if it is strictly greater than every 4-neighbor that exists. Return the number of peaks in a grid.
public static boolean isPeak(int[][] grid, int r, int c) {
int v = grid[r][c];
if (r > 0 && grid[r - 1][c] >= v) {
return false;
}
if (r < grid.length - 1 && grid[r + 1][c] >= v) {
return false;
}
if (c > 0 && grid[r][c - 1] >= v) {
return false;
}
if (c < grid[0].length - 1 && grid[r][c + 1] >= v) {
return false;
}
return true;
}
public static int countPeaks(int[][] grid) {
int count = 0;
for (int r = 0; r < grid.length; r++) {
for (int c = 0; c < grid[0].length; c++) {
if (isPeak(grid, r, c)) {
count++;
}
}
}
return count;
}
Step 1 — Read the helper. isPeak is the "all" pattern: any neighbor that is at least as large is a counterexample. Each test puts its bounds check before &&, so missing neighbors are skipped rather than read.
Step 2 — Trace the candidates in h.
| Element | Neighbors that exist | Peak? |
|---|---|---|
| 9 at (1, 1) | 5, 8, 6, 1 | yes |
| 7 at (1, 3) | 4 above, 3 below, 1 to the left | yes: it is on the right edge |
| 8 at (2, 1) | 9 above, 2, 4 | no: 9 is larger |
| 5 at (0, 1) | 9 below, 3, 2 | no |
| 6 at (1, 0) | 3, 2, 9 | no |
Every other element has a larger neighbor right beside it.
Step 3 — Answer. countPeaks(h) returns 2.
Step 4 — Why not use the interior loop? An interior-only loop needs no guards, but it never visits edge elements, so it would miss the 7 and return 1. Use interior bounds only when the task excludes the edges.
AP-Style Application 🎯
int[][] a = {
{1, 6, 2},
{7, 3, 8},
{2, 9, 4}
};
Part 5: Building and Transforming Grids
🔢 2D Array Algorithms
Part 5 of 7 — Building and Transforming Grids
So far every algorithm read a grid or changed it in place. This part builds new data from a grid (CED Topic 4.13): a turned or flipped copy, a 2D grid made from a 1D array, a 1D array or an ArrayList made from a grid, and results gathered from a grid of objects.
| Task | New structure | Index rule |
|---|---|---|
| Transpose | new int[cols][rows] | result[c][r] = grid[r][c] |
| Mirror left to right | new int[rows][cols] | result[r][cols - 1 - c] = grid[r][c] |
| Flip top to bottom | new int[rows][cols] | result[rows - 1 - r][c] = grid[r][c] |
| 1D array to grid, row-major | new int[rows][cols] | grid[k / cols][k % cols] = arr[k] |
| Grid to 1D array, row-major | new int[rows * cols] | arr[r * cols + c] = grid[r][c] |
| Grid to list | an ArrayList of Integer | list.add(grid[r][c]) when the value qualifies |
🔑 Key Concept: When the result has a different shape, write its dimensions down before writing any loop. Then check every subscript against the array it indexes:
result[c][r]must fit the result, andgrid[r][c]must fit the original.
Transpose: Rows Become Columns
public static int[][] transpose(int[][] grid) {
int[][] result = new int[grid[0].length][grid.length];
for (int r = 0; r < grid.length; r++) {
for (int c = 0; c < grid[0].length; c++) {
result[c][r] = grid[r][c];
}
}
return result;
}
transpose({{1, 2, 3}, {4, 5, 6}}) returns the 3 x 2 grid {{1, 4}, {2, 5}, {3, 6}}. Row 0 of the original, 1 2 3, is now column 0.
Wrong dimensions. With new int[grid.length][grid[0].length] the result is 2 x 3, the same shape as the original. When c reaches 2 in row 0, the loop writes result[2][0], and row index 2 does not exist in a 2-row array, so Java throws an ArrayIndexOutOfBoundsException.
Mirror and Flip
int rows = grid.length;
int cols = grid[0].length;
int[][] mirror = new int[rows][cols];
int[][] flip = new int[rows][cols];
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
mirror[r][cols - 1 - c] = grid[r][c]; // left to right
flip[rows - 1 - r][c] = grid[r][c]; // top to bottom
}
}
| Original | Mirror | Flip | Turned 90 degrees clockwise |
|---|---|---|---|
{{1, 2, 3}, {4, 5, 6}} | {{3, 2, 1}, {6, 5, 4}} | {{4, 5, 6}, {1, 2, 3}} | {{4, 1}, {5, 2}, {6, 3}} |
The clockwise turn combines the two ideas: new int[cols][rows] and result[c][rows - 1 - r] = grid[r][c].
Why a New Grid?
Writing the mirror back into the same grid, grid[r][cols - 1 - c] = grid[r][c], overwrites values before they are read. Row {1, 2, 3} becomes {1, 2, 1}: the 3 is lost when the 1 is copied over it. Either build a new grid or swap pairs with a temp variable, as Part 3 did for reversing rows.
Concept Check 🎯
int[][] q = {{1, 2}, {3, 4}, {5, 6}};
A 1D Array Into a Grid (Row-Major)
Element k of the 1D array goes to row k / cols and column k % cols: integer division counts the full rows before it, and the remainder is its place in the current row.
public static int[][] toGrid(int[] arr, int rows, int cols) {
int[][] grid = new int[rows][cols];
for (int k = 0; k < arr.length; k++) {
grid[k / cols][k % cols] = arr[k];
}
return grid;
}
| Call | Result |
|---|---|
toGrid({10, 20, 30, 40, 50, 60}, 2, 3) | {{10, 20, 30}, {40, 50, 60}} |
same, with grid[k % rows][k / rows] (column-major fill) | {{10, 30, 50}, {20, 40, 60}} |
same, with grid[k / rows][k % rows] (wrong divisor) | ArrayIndexOutOfBoundsException when k is 4 |
In a 3 x 4 grid, k = 7 lands at row 7 / 4 = 1, column 7 % 4 = 3.
A Grid Into a 1D Array
int[] flat = new int[grid.length * grid[0].length];
int k = 0;
for (int r = 0; r < grid.length; r++) {
for (int c = 0; c < grid[0].length; c++) {
flat[k] = grid[r][c]; // or flat[r * grid[0].length + c]
k++;
}
}
Both forms flatten {{1, 2, 3}, {4, 5, 6}} to {1, 2, 3, 4, 5, 6}. The formula multiplies by the number of columns, because each earlier row holds that many elements. Multiplying by the number of rows instead writes two values into index 2 and gives {1, 2, 4, 5, 6, 0}.
To copy just one column into a 1D array, the new array has one slot per row: int[] col = new int[grid.length]; then col[r] = grid[r][c]; for each r. Column 3 of the Part 2 sales grid gives {4, 15, 15}.
A Grid Into an ArrayList
When the number of results is not known in advance, collect them in an ArrayList (the Quick Reference methods add, get, set, remove and size are enough):
import java.util.ArrayList;
public static ArrayList<Integer> evensList(int[][] grid) {
ArrayList<Integer> result = new ArrayList<Integer>();
for (int r = 0; r < grid.length; r++) {
for (int c = 0; c < grid[0].length; c++) {
if (grid[r][c] % 2 == 0) {
result.add(grid[r][c]); // autoboxed to Integer
}
}
}
return result;
}
evensList(sales) returns [12, 4, 18, 6], in row-major order. Going the other way, a list of 6 values can fill a 3 x 2 grid with grid[k / 2][k % 2] = list.get(k);: the list [8, 3, 5, 1, 9, 4] becomes {{8, 3}, {5, 1}, {9, 4}}.
Applied Recall ✍️
-
A 1D array is copied into a 3 x 4 grid in row-major order. In which row does
arr[10]land? _______ -
A 4 x 5 grid is flattened in row-major order. At what index of the 1D array does the element at row 1, column 2 end up? _______
-
What does
evensList(new int[][] {{3, 8, 6}, {5, 2, 7}}).size()return? _______
Grids of Objects
A 2D array of objects stores references, and any slot that was never assigned holds null. Calling a method through null throws a NullPointerException, so every traversal checks the slot first.
public class Plant {
private String name;
private int height;
public Plant(String n, int h) {
name = n;
height = h;
}
public String getName() { return name; }
public int getHeight() { return height; }
}
Plant[][] garden = new Plant[2][3]; // every slot starts as null
garden[0][0] = new Plant("fern", 30);
garden[0][2] = new Plant("mint", 12);
garden[1][1] = new Plant("sage", 48);
Average Height of the Plants That Exist
int total = 0;
int count = 0;
for (int r = 0; r < garden.length; r++) {
for (int c = 0; c < garden[0].length; c++) {
if (garden[r][c] != null) {
total += garden[r][c].getHeight();
count++;
}
}
}
double avg = (double) total / count; // 90 / 3 = 30.0
The divisor is count, the number of plants, not the 6 slots: dividing by 6 gives 15.0. Without the null check, the loop throws a NullPointerException at garden[0][1].
The Tallest Plant's Name
Plant tallest = null;
for (int r = 0; r < garden.length; r++) {
for (int c = 0; c < garden[0].length; c++) {
Plant p = garden[r][c];
if (p != null && (tallest == null || p.getHeight() > tallest.getHeight())) {
tallest = p;
}
}
}
// tallest.getName() is "sage"
The first plant found becomes the first candidate, which is the object version of starting a maximum at the first element. The null test must come first in each && and ||, so the method call is skipped whenever the reference is null.
Misconceptions When Building Grids
| Misconception | What actually happens |
|---|---|
| "A transposed grid has the same dimensions." | It is new int[cols][rows]; the same shape throws unless the grid is square |
"Row-major position k is at [k / rows][k % rows]." | divide by the number of columns |
| "Mirroring can copy straight back into the same grid." | values are overwritten before they are read |
"A new Plant[2][3] holds six Plant objects." | it holds six null references until objects are assigned |
| "Average over a grid of objects divides by rows x cols." | divide by the number of real objects counted |
AP-Style Application 🎯
Segment A
Plant[][] yard = new Plant[2][2];
yard[0][1] = new Plant("ivy", 20);
yard[1][0] = new Plant("moss", 5);
int total = 0;
int count = 0;
for (int r = 0; r < yard.length; r++) {
for (int c = 0; c < yard[0].length; c++) {
if (yard[r][c] != null && yard[r][c].getHeight() > 0) {
total += yard[r][c].getHeight();
count++;
}
}
}
System.out.println((double) total / count);
Part 6: AP-Style Practice
🔢 2D Array Algorithms
Part 6 of 7 — AP-Style Practice
Question 4 of the free-response section is the 2D array question. It typically describes a class whose instance variable is a 2D array and asks for code that builds the grid, traverses all or part of it, and reports a count, a location or a changed grid. Multiple-choice questions trace the same algorithms. This part practices both, using only the Java Quick Reference subset.
How to Attack a 2D Array Question
| Step | Do this |
|---|---|
| 1 | Draw the grid with row numbers down the side and column numbers across the top. |
| 2 | Write the number of rows (grid.length) and columns (grid[0].length) next to it. |
| 3 | For each loop, note which index it controls and its first and last value. |
| 4 | For every r - 1, r + 1, c - 1 or c + 1, find the guard that keeps it in bounds. |
| 5 | When the code changes the grid while reading it, redraw the grid after each row. |
🔑 Key Concept: Free-response rubrics reward each separate skill: traversing the whole grid, staying in bounds, applying the condition, and returning the right result. A solution with one bug still earns the points for the skills it shows, so write the full method even when one step is uncertain.
Practice Set 1: Tracing 🎯
Segment A
int[][] m = {{2, 5, 1}, {4, 3, 6}};
int result = 0;
for (int c = 0; c < m[0].length; c++) {
int best = m[0][c];
for (int r = 1; r < m.length; r++) {
if (m[r][c] > best) {
best = m[r][c];
}
}
result += best;
}
Segment B
int[][] g = {{1, 2, 3}, {4, 5, 6}};
for (int r = 0; r < g.length; r++) {
for (int c = 1; c < g[0].length; c++) {
g[r][c] += g[r][c - 1];
}
}
Segment C
int[][] d = {{1, 2}, {3, 4}, {5, 6}};
for (int r = 1; r < d.length; r++) {
for (int c = 0; c < d[0].length; c++) {
d[r][c] = d[r - 1][c];
}
}
FRQ-Style Task — ElevationMap
A hiking app stores ground heights in a grid.
public class ElevationMap {
private int[][] heights;
/** Precondition: data.length is a multiple of numRows, and data.length > 0.
* Fills heights in row-major order using every value of data. */
public ElevationMap(int[] data, int numRows) { /* part (a) */ }
/** A location is flat if every 4-neighbor that exists differs from it
* by at most 1. Returns the number of flat locations. */
public int countFlatSpots() { /* part (b) */ }
}
Example. new ElevationMap(new int[] {5, 5, 6, 9, 4, 5, 5, 8, 2, 4, 6, 6}, 3) builds:
| col 0 | col 1 | col 2 | col 3 | |
|---|---|---|---|---|
| row 0 | 5 | 5 | 6 | 9 |
| row 1 | 4 | 5 | 5 | 8 |
| row 2 | 2 | 4 | 6 | 6 |
countFlatSpots() returns 3: the locations (0, 0), (0, 1) and (1, 1). For instance, the 6 at (2, 2) is not flat, because its left neighbor 4 differs by 2.
Part (a) Solution
public ElevationMap(int[] data, int numRows) {
int numCols = data.length / numRows;
heights = new int[numRows][numCols];
for (int k = 0; k < data.length; k++) {
heights[k / numCols][k % numCols] = data[k];
}
}
The number of columns is not given, so it is computed first. The instance variable is assigned, not redeclared: writing int[][] heights = new int[...] would create a local variable and leave the field null.
Part (b) Solution
public int countFlatSpots() {
int count = 0;
for (int r = 0; r < heights.length; r++) {
for (int c = 0; c < heights[0].length; c++) {
if (isFlat(r, c)) {
count++;
}
}
}
return count;
}
private boolean isFlat(int r, int c) {
int h = heights[r][c];
if (r > 0 && Math.abs(heights[r - 1][c] - h) > 1) {
return false;
}
if (r < heights.length - 1 && Math.abs(heights[r + 1][c] - h) > 1) {
return false;
}
if (c > 0 && Math.abs(heights[r][c - 1] - h) > 1) {
return false;
}
if (c < heights[0].length - 1 && Math.abs(heights[r][c + 1] - h) > 1) {
return false;
}
return true;
}
A private helper method is allowed and keeps the four neighbor tests out of the nested loops. Math.abs turns "differs by at most 1" into one comparison in either direction.
Rubric Checklist
| Part | A full-credit answer |
|---|---|
| (a) | computes the number of columns from data.length and numRows |
| (a) | creates the array with the right dimensions and assigns it to the instance variable |
| (a) | places every element of data at [k / numCols][k % numCols] (or uses a separate counter) |
| (b) | traverses every location of heights without going out of bounds |
| (b) | guards each neighbor before reading it, and compares with Math.abs(...) > 1 or an equivalent |
| (b) | counts a location only when all existing neighbors pass, and returns the count |
Practice Set 2: Reasoning About the Solution 🎯
Applied Recall ✍️
-
What does
countFlatSpots()return for the grid{{3, 3}, {4, 6}}? _______ -
After
new ElevationMap(new int[] {2, 4, 6, 8, 10, 12, 14, 16}, 2), what isheights[1][1]? _______ -
How many comparisons does
isSymmetricfrom Part 4 make on a symmetric 6 x 6 grid? _______
Common FRQ Deductions on 2D Arrays
| Mistake | Why it costs points |
|---|---|
grid.length used as the number of columns | wrong bound on non-square grids: skipped columns or an exception |
Reading grid[r - 1][c] with no r > 0 guard (or the guard after &&) | the first row reads index -1 |
| Redeclaring the instance variable inside the constructor | the field stays null and later methods fail |
| Dividing by the wrong count, or using int division for an average | the result is wrong or loses its fraction |
| Returning or deciding inside the loops too early | the method answers from part of the grid |
| Changing the grid while still reading values that the result depends on | later elements use already-changed values |
| Printing the answer instead of returning it | the method must return a value to its caller |
🎯 AP Connection: Name your loop variables
randc(orrowandcol) and keep them in that order in every subscript. Most 2D errors on the exam come from writinggrid[c][r], which works only by accident on square grids.
Part 7: Synthesis Review
🔢 2D Array Algorithms
Part 7 of 7 — Synthesis Review
This part ties together the 2D array algorithms of CED Topic 4.13 and the skills that free-response question 4 tests. Use the table as a checklist, then work through the mixed questions.
The Topic on One Page
| Algorithm | Key fact | Typical trap |
|---|---|---|
| Total and average (Part 2) | divide by grid.length * grid[0].length, after a cast to double | int division, or dividing by the rows only |
| Max or min with location (Part 2) | keep both indices; start at [0][0]; > keeps the first tie in row-major order | starting at 0, or returning only the value |
| Any / all and search (Part 2) | decide inside the inner loop; default return after both loops | a default return between the loops checks only row 0 |
| Per-row and per-column results (Part 3) | new int[grid.length] for rows, new int[grid[0].length] for columns; the outer loop picks which | a running sum that is never reset |
| Swaps and reversals (Part 3) | rows swap by reference; columns need a loop; reverse to half the length | full-length reversal undoes itself |
| Neighbors (Part 4) | guard each direction, and put the guard first in && | reading index -1 or length |
| Diagonals and regions (Part 4) | anti-diagonal [i][n - 1 - i]; interior 1 to length - 2; blocks stop at length - 2 | interior loops skip edge elements |
| Building grids (Part 5) | transpose is new int[cols][rows]; row-major k is [k / cols][k % cols] | dividing by the number of rows |
| Grids of objects (Part 5) | check for null before calling a method | NullPointerException on empty slots |
Worked Example: One Grid, Five Algorithms
int[][] w = {
{4, 7, 2},
{9, 3, 8},
{1, 6, 5},
{7, 2, 9}
};
Step 1 — Shape. w.length is 4 rows and w[0].length is 3 columns, so a full traversal visits 12 elements.
Step 2 — Row and column totals. rowTotals(w) is {13, 20, 12, 18}, so bestRow(w) returns 1. colTotals(w) is {21, 18, 24}: a length-3 array, one slot per column.
Step 3 — Maximum with location. The value 9 appears at (1, 0) and (3, 2). With > the row-major search keeps (1, 0); with >= it ends at (3, 2).
Step 4 — Search order. findValue(w, 7) returns {0, 1} after examining 2 elements. A column-major search reaches the 7 in column 0 first and returns {3, 0}.
Step 5 — Neighbors. The 3 at (1, 1) is interior, and all four of its neighbors (7, 6, 9, 8) are larger. countPeaks(w) returns 6: the 7, 9, 8, 6, 7 and 9 each beat every neighbor they have, including the two corner values in row 3, which have only two neighbors each.
Step 6 — Transpose. transpose(w) is a 3 x 4 grid: {{4, 9, 1, 7}, {7, 3, 6, 2}, {2, 8, 5, 9}}. Row 1 of the result is column 1 of w.
Mixed Review 1 🎯
int[][] v = {
{3, 1, 4},
{1, 5, 9},
{7, 6, 5}
};
Segment A
int s = 0;
for (int i = 0; i < v.length; i++) {
s += v[i][i] - v[i][v.length - 1 - i];
}
Segment B
int count = 0;
for (int c = 0; c < v[0].length; c++) {
boolean allOdd = true;
for (int r = 0; r < v.length; r++) {
if (v[r][c] % 2 == 0) {
allOdd = false;
}
}
if (allOdd) {
count++;
}
}
Segment C
ArrayList<Integer> list = new ArrayList<Integer>();
for (int c = 0; c < v[0].length; c++) {
for (int r = 0; r < v.length; r++) {
if (v[r][c] > 4) {
list.add(v[r][c]);
}
}
}
Count Reference
| Region or algorithm | Elements or comparisons for a grid with R rows and C columns |
|---|---|
| Full traversal, or a search for a missing value | R x C |
| Interior elements | (R - 2) x (C - 2) |
| 2 x 2 blocks | (R - 1) x (C - 1) |
| Neighbors of one element | 4-neighbors: 2 at a corner, 3 on an edge, 4 inside; 8-neighbors: 3, 5 or 8 |
| Symmetry check on an n x n grid | n(n - 1) / 2 comparisons when symmetric |
| Elements on either diagonal of an n x n grid | 2n when n is even, 2n - 1 when n is odd |
Error Catalogue
| Symptom | Likely cause | Fix |
|---|---|---|
| ArrayIndexOutOfBoundsException only on non-square grids | grid.length used for columns, or grid[c][r] | columns are grid[0].length; keep [r][c] order |
| ArrayIndexOutOfBoundsException at index -1 | a neighbor read with no r > 0 or c > 0 guard, or the guard after && | guard first |
| the last row always "wins" | a per-row sum declared outside the outer loop | declare it inside the outer loop |
| a search or "all" check ignores later rows | a return between the two closing braces | move the default return after both loops |
| a mirrored or reversed row repeats values | copying in place without a temp variable or a new grid | swap pairs, or build a new grid |
| NullPointerException in a grid of objects | a method called on an empty slot | test != null first |
| average is a whole number | int division | cast to double before dividing |
🎯 AP Connection: On question 4, read the class header first and note the instance variable's name and type. Then write the nested loops with
rovergrid.lengthandcovergrid[0].lengthbefore you think about the condition: that skeleton earns the traversal point.
Quick Evaluation 🔍
Mixed Review 2 🎯