9 of 9
Before writing any grid function:
rows = len(grid), cols = len(grid[0])grid[row][col] — row first, then col0 <= r < rows and 0 <= c < cols# Always check before accessing a cell if 0 <= r < rows and 0 <= c < cols: val = grid[r][c] # safe
Missing this causes IndexError or silent wrong answers.
# Option 1: set of tuples (easy) visited = set() visited.add((row, col)) if (row, col) in visited: ... # Option 2: boolean grid (faster for large grids) visited = [[False] * cols for _ in range(rows)] visited[row][col] = True if visited[row][col]: ...
Both work. Sets are simpler to write in a contest.
| Problem | Use |
|---|---|
| Does a path exist? | DFS |
| Count all regions / islands | DFS |
| Flood fill | DFS |
| Shortest path length | BFS |
| Minimum steps to reach target | BFS |
Wrong index order:
# WRONG — trying to use (x, y) like math coordinates grid[col][row] # RIGHT — grid is indexed row first grid[row][col]
Forgetting to mark visited before recursing:
# WRONG — infinite loop if two neighbors point to each other def dfs(r, c): dfs(r+1, c) # visits (r+1,c), which calls dfs(r,c) again → infinite! # RIGHT — mark before recursing def dfs(r, c): visited.add((r, c)) dfs(r+1, c)
Not initializing cols correctly for non-square grids:
# WRONG for non-square grids cols = len(grid) # this is rows! # RIGHT rows = len(grid) cols = len(grid[0])
is_valid(r, c) if you need bounds checks repeatedly