Skip to content
🎯⭐ INTERACTIVE LESSON

2D Arrays

Learn step-by-step with interactive practice!

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;
}
AlgorithmApproach
Row sum/avgFix row, loop columns
Column sum/avgFix column, loop rows
SearchNested loops, return true if found
Count matchesNested loops, increment counter
Find max/minInitialize 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 ✍️

  1. To process a single row, fix the _______ index and loop over columns.

  2. Diagonal elements in a square matrix satisfy the condition row == _______.

  3. 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.length for the number of rows and matrix[0].length for 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.

AlgorithmAnswers the questionResult
Total and averageWhat is the sum of every element? The mean?int, then double
Maximum or minimum with locationWhat is the extreme value, and in which row and column?two indices
CountHow many elements meet a condition?int
At least one / allDoes any element qualify? Does every element?boolean
Search for a locationWhere 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.length is the number of rows and grid[0].length is the number of columns. The number of elements is grid.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.

ExpressionValueWhy
(double) total / (sales.length * sales[0].length)12.5the cast makes the division a double division
total / (sales.length * sales[0].length)12int / int drops the .5, even if stored in a double (12.0)
(double) total / sales.length50.0divides 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.

TestResultReason
>row 1, column 1a later 21 only ties, so the location stays
>=row 2, column 2every 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};
}
CallReturnsElements 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:

RowElementsAt least 12.5
012, 7, 19, 419
19, 21, 3, 1521, 15
218, 6, 21, 1518, 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 withHoldsMistake to avoid
new int[grid.length]one value per rowusing 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 columnusing 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 boundResult for {{1, 2, 3, 4}, {5, 6, 7, 8}}
c < n / 2{{4, 3, 2, 1}, {8, 7, 6, 5}}
c < nunchanged: 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 totalAverage
031578.75
133784.25
231077.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}
};
  1. What value is at index 3 of the array returned by colTotals(g)? _______

  2. What does bestRow(g) return? _______

  3. 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.

RegionIndex patternGuard 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 1a 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 elementsr from 1 to length - 2none: every interior element has all 4 neighbors
2 x 2 blockstop-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 that r - 1 is at least 0. Before you read grid[r + 1][c], prove that r + 1 is at most grid.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;
}
CallNeighbors that existReturns
neighborSum(h, 1, 1)up 5, down 8, left 6, right 120
neighborSum(h, 0, 0)down 6, right 511
neighborSum(h, 0, 2)down 1, left 5, right 410

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 = 0Result
r > 0 && grid[r - 1][c] > 5false; the array is never read
grid[r - 1][c] > 5 && r > 0ArrayIndexOutOfBoundsException: 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 h231714252215

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.

ElementNeighbors that existPeak?
9 at (1, 1)5, 8, 6, 1yes
7 at (1, 3)4 above, 3 below, 1 to the leftyes: it is on the right edge
8 at (2, 1)9 above, 2, 4no: 9 is larger
5 at (0, 1)9 below, 3, 2no
6 at (1, 0)3, 2, 9no

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.

TaskNew structureIndex rule
Transposenew int[cols][rows]result[c][r] = grid[r][c]
Mirror left to rightnew int[rows][cols]result[r][cols - 1 - c] = grid[r][c]
Flip top to bottomnew int[rows][cols]result[rows - 1 - r][c] = grid[r][c]
1D array to grid, row-majornew int[rows][cols]grid[k / cols][k % cols] = arr[k]
Grid to 1D array, row-majornew int[rows * cols]arr[r * cols + c] = grid[r][c]
Grid to listan ArrayList of Integerlist.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, and grid[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
    }
}
OriginalMirrorFlipTurned 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;
}
CallResult
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 ✍️

  1. A 1D array is copied into a 3 x 4 grid in row-major order. In which row does arr[10] land? _______

  2. 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? _______

  3. 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

MisconceptionWhat 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

StepDo this
1Draw the grid with row numbers down the side and column numbers across the top.
2Write the number of rows (grid.length) and columns (grid[0].length) next to it.
3For each loop, note which index it controls and its first and last value.
4For every r - 1, r + 1, c - 1 or c + 1, find the guard that keeps it in bounds.
5When 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 0col 1col 2col 3
row 05569
row 14558
row 22466

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

PartA 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 ✍️

  1. What does countFlatSpots() return for the grid {{3, 3}, {4, 6}}? _______

  2. After new ElevationMap(new int[] {2, 4, 6, 8, 10, 12, 14, 16}, 2), what is heights[1][1]? _______

  3. How many comparisons does isSymmetric from Part 4 make on a symmetric 6 x 6 grid? _______

Common FRQ Deductions on 2D Arrays

MistakeWhy it costs points
grid.length used as the number of columnswrong 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 constructorthe field stays null and later methods fail
Dividing by the wrong count, or using int division for an averagethe result is wrong or loses its fraction
Returning or deciding inside the loops too earlythe method answers from part of the grid
Changing the grid while still reading values that the result depends onlater elements use already-changed values
Printing the answer instead of returning itthe method must return a value to its caller

🎯 AP Connection: Name your loop variables r and c (or row and col) and keep them in that order in every subscript. Most 2D errors on the exam come from writing grid[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

AlgorithmKey factTypical trap
Total and average (Part 2)divide by grid.length * grid[0].length, after a cast to doubleint 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 orderstarting at 0, or returning only the value
Any / all and search (Part 2)decide inside the inner loop; default return after both loopsa 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 whicha running sum that is never reset
Swaps and reversals (Part 3)rows swap by reference; columns need a loop; reverse to half the lengthfull-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 - 2interior 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 methodNullPointerException 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 algorithmElements or comparisons for a grid with R rows and C columns
Full traversal, or a search for a missing valueR x C
Interior elements(R - 2) x (C - 2)
2 x 2 blocks(R - 1) x (C - 1)
Neighbors of one element4-neighbors: 2 at a corner, 3 on an edge, 4 inside; 8-neighbors: 3, 5 or 8
Symmetry check on an n x n gridn(n - 1) / 2 comparisons when symmetric
Elements on either diagonal of an n x n grid2n when n is even, 2n - 1 when n is odd

Error Catalogue

SymptomLikely causeFix
ArrayIndexOutOfBoundsException only on non-square gridsgrid.length used for columns, or grid[c][r]columns are grid[0].length; keep [r][c] order
ArrayIndexOutOfBoundsException at index -1a 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 loopdeclare it inside the outer loop
a search or "all" check ignores later rowsa return between the two closing bracesmove the default return after both loops
a mirrored or reversed row repeats valuescopying in place without a temp variable or a new gridswap pairs, or build a new grid
NullPointerException in a grid of objectsa method called on an empty slottest != null first
average is a whole numberint divisioncast 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 r over grid.length and c over grid[0].length before you think about the condition: that skeleton earns the traversal point.

Quick Evaluation 🔍

Mixed Review 2 🎯