Explore 2D Matrix algorithms including BFS and DFS traversals.
6 algorithms1 race7 problems
6 algorithms. Each one stands alone.
Same input, side by side. Watch who wins.
Grid problems treat a 2D matrix as a map: cells are places and you move between neighbours. They show up in game maps, paint tools and many interview questions.
Each page turns a row and column pair into a set of neighbours and decides which of them to visit next. Grid BFS, the maze pathfinder, the Minesweeper reveal and Rotting Oranges use a queue, so cells are reached in rings by distance. Grid DFS and Number of Islands use a stack, so they run down one path before backing up. Spiral traversal uses four moving walls instead of visited marks, so its path is fixed by the shape of the grid alone. All seven touch each cell a constant number of times, O(R times C) in total.
Start with grid BFS and DFS together, since the other pages build on them. One test picks between them: if the answer is a distance or a number of rounds, use a queue; if it is yes or no, or a region to label, either works and DFS is shorter to write. On large grids, give DFS an explicit stack: recursion can overflow.