Grids
GOALBuild a table with rows and columns, and walk through it.
A chessboard, a maze, the pixels of a picture — all of them are grids. Think of an array of arrays: the first index is the ROW, the second is the COLUMN.
ON THIS PAGE
//THE EXAMPLE
#include <iostream>
#include <vector>
using namespace std;
int main() {
int rows = 3, cols = 4;
vector<vector<int>> g(rows, vector<int>(cols, 0));
g[0][0] = 1;
g[1][2] = 7;
g[2][3] = 9;
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
cout << g[r][c] << " ";
}
cout << endl;
}
return 0;
}1 0 0 0 0 0 7 0 0 0 0 9
//LINE BY LINE
Watch it run
Three rows, four columns. Every cell starts at 0.
Ways to walk a grid
Rows outside, columns inside — that is the usual shape. Swap them and you read the grid column by column, which is sometimes exactly what you want.
// row by row
for (int r = 0; r < rows; r++)
for (int c = 0; c < cols; c++)
cout << g[r][c];
// column by column
for (int c = 0; c < cols; c++)
for (int r = 0; r < rows; r++)
cout << g[r][c];The main diagonal is every cell where r == c. The other diagonal is where r + c == n - 1.
The neighbouring cells
Most grid problems ask you to look at the cells next to this one. Keeping the four directions in two small arrays keeps the code clean.
int dr[4] = {-1, 1, 0, 0}; // up, down, left, right
int dc[4] = {0, 0, -1, 1};
for (int k = 0; k < 4; k++) {
int nr = r + dr[k];
int nc = c + dc[k];
if (nr < 0 || nr >= rows) continue; // outside
if (nc < 0 || nc >= cols) continue;
// nr, nc is a real neighbour
}Check the bounds FIRST. In Python a negative index does not error — g[-1] gives the last row and the answer goes quietly wrong.