Foundations
Linear Structures
Hashing
Array and String Patterns
Recursion, Search, and Sorting
Problem Solving Patterns
Algorithm Searching
Sorting Algorithms
Array Algorithms
Grid Algorithms
Linear Structure Algorithms
Hashing Algorithms
Recursion and Backtracking
Greedy Algorithms
Tree and Heap Algorithms
Graph Algorithms
Dynamic Programming Algorithms
String Algorithms
Math Algorithms
Keyboard ready
Space plays. Arrow keys step. R restarts.
LAB Matrix Neighbors Lab
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
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] 1.0x