DSA Visualizer
GRID

Grid Algorithms

BFS and DFS on a 2D array, one step at a time: fill a region, count the islands, and find the shortest way through a maze. Click cells to change the grid, or bring your own from the 2D Array Visualizer.

Pick an algorithm to step through

Three questions, one search

A grid is a graph in disguise: every cell is a node with up to four neighbours. All three algorithms walk that graph while remembering which cells they have already seen, so each one costs about rows × cols steps. What differs is the question being asked and what has to be remembered to answer it.

How the three grid algorithms compare
AlgorithmQuestionRemembersOutput
Flood fillWhich cells are connected to this one?A queue (BFS) or the call stack (DFS)The filled region
Number of islandsHow many separate regions are there?A visited mark on every land cellA count
BFS shortest pathWhat is the fewest steps from A to B?A queue, a distance and a parent per cellThe distance and the route

Which one should you learn first?

Start with flood fill: it is the search itself, with nothing else attached, and you can watch BFS and DFS cover the same cells in different orders. Then number of islands, which wraps that search in a loop and a counter. Finish with BFS shortest path, where the order of the search finally matters and the queue earns its keep.

Each page keeps your grid when you switch, so draw one maze and run all three on it.

Grid algorithm questions

What is a grid algorithm?

A graph algorithm run on a 2D array, where every cell is a node joined to its four neighbours. Flood fill, counting islands and finding the shortest path through a maze are the three every course starts with, and they are the same search, breadth-first or depth-first, asked different questions.

When should I use BFS instead of DFS on a grid?

Use BFS whenever distance matters, because it explores in rings and the first time it reaches a cell is by the fewest steps. Use DFS when you only need to know what is connected, such as filling a region or counting islands, because the recursive version is the shortest code. On very large regions prefer BFS or an explicit stack to avoid deep recursion.

Do these work with diagonal moves?

Yes, if you add the four diagonal neighbours to the search. The default here is 4-connected, which is what LeetCode 733 and 200 use. LeetCode 1091 is the 8-connected shortest path.

Can I use my own grid?

Yes. Click cells directly to move the start, toggle walls or switch land and water, use the Random and Clear buttons, or build a grid in the 2D Array Visualizer and use the Run on this grid links under it. Copy link reopens the same grid, start, target and step.