Your free access ends in 7 days — and you haven’t tried it yet. Watch one algorithm run, start to finish. It takes about two minutes.

Try one problem
0
Concept

Matrices

A grid is a graph · DFS the 4 neighbours
step 1 / 99
4 × 4 grid as a graph
a
b
c
d
e
f
g
h
i
j
k
l
m
n
o
p
Flood DFS on a grid
1dfs(r, c):
2 mark visited[r][c] = true
3 for (dr, dc) in [up, down, left, right]:
4 nr, nc = r+dr, c+dc
5 if out of bounds: skip
6 if visited[nr][nc]: skip
7 dfs(nr, nc) // recurse
8 return // backtrack
9dfs(startR, startC)
state
  • rows4
  • cols4
  • neighbours4-directional

line 1A grid is just a graph in disguise. Each cell is a NODE, and the edges run to its four orthogonal neighbours: up, down, left, right. No diagonals. DFS on a grid is the same depth-first walk you already know — pick a start, dive into a neighbour, and keep diving until you hit a wall.