Direction Arrays in Grid Problems
Direction arrays are used in grid-based problems to move in the four or eight possible directions without writing separate code for each move.
Why Use Direction Arrays?
Without direction arrays:
row - 1, col // Up
row + 1, col // Down
row, col - 1 // Left
row, col + 1 // Right
This becomes repetitive and error-prone.
With direction arrays:
int[] dr = {-1, 0, 1, 0};
int[] dc = {0, 1, 0, -1};
Now all directions can be traversed using a loop.
4-Directional Movement
int[] dr = {-1, 0, 1, 0};
int[] dc = {0, 1, 0, -1};
| Index | Direction | Row Change | Col Change |
|---|---|---|---|
| 0 | Up | -1 | 0 |
| 1 | Right | 0 | +1 |
| 2 | Down | +1 | 0 |
| 3 | Left | 0 | -1 |
Traversal:
for(int i = 0; i < 4; i++) {
int nr = row + dr[i];
int nc = col + dc[i];
}
Example
Current Cell:
row = 2;
col = 3;
Generated Neighbors:
(1,3) // Up
(2,4) // Right
(3,3) // Down
(2,2) // Left
Boundary Check
Always check whether the new cell is inside the grid.
if(nr >= 0 && nr < n &&
nc >= 0 && nc < m) {
}
8-Directional Movement
Used in problems where diagonal movement is allowed.
int[] dr = {-1,-1,-1,0,0,1,1,1};
int[] dc = {-1,0,1,-1,1,-1,0,1};
Directions:
↖ ↑ ↗
← X →
↙ ↓ ↘
Traversal:
for(int i = 0; i < 8; i++) {
int nr = row + dr[i];
int nc = col + dc[i];
}
Where It Is Used?
Number of Islands
Rotten Oranges
Flood Fill
Shortest Path in Binary Matrix
Path With Minimum Effort
BFS on Grid
DFS on Grid
Multi-source BFS
Complete Template
int[] dr = {-1, 0, 1, 0};
int[] dc = {0, 1, 0, -1};
for(int i = 0; i < 4; i++) {
int nr = row + dr[i];
int nc = col + dc[i];
if(nr >= 0 && nr < n &&
nc >= 0 && nc < m) {
// process neighbour
}
}
Key Insight
Think of dr and dc as instructions for movement.
newRow = currentRow + dr[i];
newCol = currentCol + dc[i];
Instead of manually writing all directions, we store movement patterns in arrays and iterate through them. This makes BFS, DFS, and Dijkstra grid solutions much cleaner and easier to maintain.