Implementing 2D Array Algorithms
| English | Chinese | Pinyin |
|---|---|---|
| nested-loop | 嵌套循环 | qiàn tào xún huán |
| main diagonal | 主对角线 | zhǔ duì jiǎo xiàn |
| indexed | 带下标 | dài xià biāo |
Grid algorithms
- 2-D algorithms combine the array patterns with nested-loop 嵌套循环 traversal.
- Sum / count / max over the whole grid: accumulate inside the inner loop.
- Search a grid: return the
[row][col]where found (or a "not found" signal). - The same accumulator/max logic, now over
rows × columnscells.
Row and column sums
- One row: fix
r, loopcover the columns, summingg[r][c]. - One column: fix
c, looprover the rows, summingg[r][c]. - Choosing which index to fix and which to loop is the key decision.
- A row sum sweeps across; a column sum sweeps down.
The diagonal
- The main diagonal 主对角线 of a square grid is the cells where row == column.
- Loop one index:
for (int i = 0; i < g.length; i++) { ... g[i][i] ... } g[0][0], g[1][1], g[2][2], …— a single loop, both indices equal.- Useful for square grids (identity checks, board diagonals).
Modifying cells
- To change a cell, use the indexed 带下标 nested loops and assign
g[r][c] = .... - The for-each version can't write back to the grid.
- Watch the two bounds — a wrong length reads or writes the wrong cell.
- Trace
[r][c]carefully, especially when rows and columns differ in count.
Decide which index to fix and which to loop — that's the difference between a row sum and a column sum. A row sum fixes r and loops c (g[r][c] across); a column sum fixes c and loops r (g[r][c] down). And modifying cells needs the indexed nested loops (g[r][c] = …); the for-each form can only read.
Summing column 0 of a grid:
int sum = 0;for (int r = 0; r < g.length; r++) { sum += g[r][0]; }- Fixes column
0, loops down the rows — a column sum.
2-D algorithms apply array patterns over nested loops: whole-grid sum/count/max/search, a row sum (fix r, loop c), a column sum (fix c, loop r), or the diagonal (g[i][i]). Modifying cells needs the indexed loops (g[r][c] = …); mind both bounds (g.length rows, g[0].length columns).
Summing column 0
g[0][0]=1, g[1][0]=4, g[2][0]=7: running sum 1, 5, 12.
To sum ONE row r, you...
A row sum fixes the row, loops the columns.
To sum ONE column c, you...
A column sum fixes the column, loops the rows.
The main diagonal of a square grid is the cells where...
g[0][0], g[1][1], g[2][2] — one index, both equal.
The for-each form can modify (write to) grid cells.
For-each is read-only; use indexed loops (g[r][c] = ...) to write.
Column 0 of {{1,2},{4,5},{7,8}} is 1, 4, 7. What is its sum?
1 + 4 + 7 = 12.
Order the steps to sum column c.
Initialise, loop the rows, accumulate, return.