Working with Columns
Part of: 2D Array
Columns Are Different A column is a vertical slice of the grid: the cells grid[0][c], grid[1][c], grid[2][c], and so on for a fixed column c. Unlike a row, a column is not a single Java array, there is no grid[][c] shortcut. To process one column you must fix the column index c and loop over the row index r. The Loop Order Flips The big idea: for column-wise processing the outer loop is the column and the inner loop is the row : the reverse of row-major traversal. - Row-wise: for r { for c { grid[r][c] } } - Column-wise: for c { for r { grid[r][c] } } In both cases the cell access is still grid[r][c], only the loop order changes. The outer bound is grid[0].length (number of columns) and the inner bound is grid.length (number of rows). Rows vs. Columns Summary - A row uses a fixed r; it is a real 1D array grid[r]. - A column uses a fixed c; it is not a stored array, so you gather it cell by cell. - Swapping which loop is outer switches you between row-wise and column-wise processing. Understanding that columns must be assembled manually, and that the loop nesting determines the traversal direction, is exactly the rows vs. columns distinction the AP exam tests. Keep grid[r][c] consta
Challenge: Largest Column Sum