Matrices

Problem shape

Beginner
0,0
0,1
0,2
0,3
1,0
1,1
1,2
1,3
2,0
2,1
2,2
2,3
Core idea

Use direction arrays to visit valid neighboring cells.

Step 1 / 5
Problem shape
Current lesson

Matrix Neighbors Lab

Matrices Beginner

Matrix Neighbors

Welcome to the Matrix Neighbors algorithm lab. Use direction arrays to visit valid neighboring cells. Use it when: Use for grid BFS, DFS, flood fill, islands, and maze problems. The time complexity is O(1) per cell, and the space complexity is O(1). The pseudocode is: dirs = [[1,0],[-1,0],[0,1],[0,-1]] for dir in dirs nr = r + dir.row nc = c + dir.col if inside grid visit grid[nr][nc] As you practice, track the state that changes and the condition that makes the algorithm stop.

Time

O(1) per cell

Space

O(1)

Pseudocode

dirs = [[1,0],[-1,0],[0,1],[0,-1]]
for dir in dirs
  nr = r + dir.row
  nc = c + dir.col
  if inside grid
    visit grid[nr][nc]
Open deeper structure lesson
1.0x