A computer can't see connections
Colored blocks fall two at a time. When four or more of the same color touch, up, down, left or right, they vanish. Blocks above them drop, another color lines up, and it vanishes too. That cascade is a chain.
You can glance at the board and say, "Four reds, touching." But hold on. A computer cannot glance. All it has is a table of numbers: this square is red, the next one is green. So how does it decide that blocks are connected?
In this simulation we slow down the three steps hidden inside a falling-block puzzle, falling, finding connected groups and clearing, and stop between them. The star of the show is a very simple and very useful algorithm called flood fill. Its ancestors are much older than any video game: a 19th-century way of escaping from mazes, and a study of how gas creeps through the pores of coal.
Spreading like a drop of ink
First, look at the board the way the computer does: a table 6 squares wide and 12 tall, in other words a two-dimensional array. Each square holds a number meaning "empty" or one of four colors. That is all.
When a pair lands, the program repeats three stages. First it lets blocks fall: in each column, floating blocks slide down until nothing is left hanging. Then it finds groups: every group of same-colored blocks that touch up, down, left or right, and the size of each. Finally it clears every group of four or more. If something was removed, it counts one more chain and goes back to the falling stage; if nothing was removed, it stops.
Finding the groups is the clever part. A thought experiment: drop a bead of ink on one square. The ink soaks only into neighboring squares of the same color, then into their neighbors, and so on. When it stops spreading, the inked squares form one group. That is the idea of flood fill. Unlike real ink, though, a computer's flood fill does not spread everywhere at once. It moves one square at a time, in a definite order, and the rule for that order is exactly what separates the BFS and DFS you are about to meet.
Of course no ink flows inside a computer. The real procedure: mark the starting square and put it into a container of "squares waiting to be examined." Take a square out of the container and look at its four neighbors; any neighbor of the same color that is not yet marked gets marked and put into the container. When the container is empty, the marked squares are exactly one group.
The marks matter. In a 2×2 square of one color, following neighbors brings you right back to where you started. Without marks you would count the same squares again and again, possibly forever.
A queue or a stack?
Change the kind of container and the spreading changes. A queue works first in, first out, like a line at a store. It gives breadth-first search, or BFS: squares are reached in order of distance from the start, like ripples on a pond. Why in order of distance? A square two steps from the start is discovered only when some one-step square is taken out, so every one-step square is already in the queue before any two-step square arrives. A queue hands squares back in the order they went in, so one step, two steps, three steps… the order never gets mixed up.
A stack works last in, first out, like a pile of plates. It gives depth-first search, or DFS, which follows one path as deep as it goes, then backs up. Both find exactly the same groups; only the visiting order differs.
Flood fill is older than any video game. Exploring a maze while marking the passages you have used is known as Trémaux's method. Édouard Lucas, the inventor of the Tower of Hanoi, described it in his 1882 book Récréations mathématiques, crediting "M. Trémaux," a former student of the École Polytechnique who had become a telegraph engineer. About a century later it became a cornerstone of computer science as depth-first search. Breadth-first search is often credited to Edward Moore, who published it in 1959 as a way to find the shortest path through a maze. In 1966 Azriel Rosenfeld and John Pfaltz described how to number the connected regions of a digital picture, which became a basic tool of image processing.
The "paint bucket" in a drawing app fills only the region connected to where you click: that is exactly this algorithm. In image analysis, when a program counts cells in a microscope photo or letters on a scanned page, it turns the image black and white and labels each connected region, a process called connected-component labeling. When your phone's camera reads the text on a document, separating the connected dark marks one by one is part of the groundwork.
What is a group, exactly?
Let's pin down what a group is. Two blocks belong to the same group if you can walk from one to the other through neighboring squares of their color. This relation is reflexive, symmetric and transitive, so the blocks split cleanly into groups: what mathematicians call a partition by an equivalence relation, and graph theorists call connected components.
In the language of graphs, squares are vertices and same-colored neighbors are edges, so groups are exactly the connected components of a graph. Graph 3-Coloring and Search Algorithms with the 8-Puzzle in this collection use the same toolkit.
Games are full of flood fill too. In Go, a group of stones with no empty points next to it is captured, and programs find the group by flood fill. In Minesweeper, clicking an empty square opens a whole connected empty region at once. And on a much larger scale, deciding which computers in a network can reach which is a connected-components question as well.
How the work grows
How much work is flood fill? Each block enters the container once and then looks at four neighbors. With blocks that is at most neighbor checks: the work grows in proportion to .
Compare a naive method that keeps no table at all and checks whether blocks touch by comparing the coordinates of every pair of blocks. How many comparisons is that? Each block has possible partners; adding that up over all blocks gives , but that counts "A with B" and "B with A" separately. So there are
pairs. It is the same count as everyone in a class shaking hands with everyone else: 780 handshakes for 40 people, whereas shaking hands only with the people at the neighboring desks takes at most 4 each. On a full board of 72 blocks that is 2,556 comparisons instead of at most . Double , and the first count doubles while the second almost quadruples.
| Number of blocks | Flood fill (at most ) | Every pair () |
|---|---|---|
| 8 | 32 | 28 |
| 16 | 64 | 120 |
| 32 | 128 | 496 |
| 72 (full board) | 288 | 2,556 |
With only a handful of blocks, the naive method is actually a little cheaper. The difference shows up as the numbers grow, and that is exactly what "how the work grows" means. How you store data can change how the work grows, and the right-hand side of the simulation shows both counts side by side. The "For comparison" line counts the naive method, which the simulation does not use. It is there only to compare.
The trap in the order of falling
Falling has a trap too. The correct way is to go column by column and pack blocks downward from the bottom; afterwards no block has an empty square below it. A naive method instead drops blocks one at a time in the order they happen to be stored, each until it hits something. If an upper block moves first, it stops on a lower block that has not fallen yet; then the lower block falls, leaving a gap. Check the groups with the gap still there and connections are missed. Procedures whose result depends on processing order are a classic source of bugs.
Chains: each round of fall → find → clear that removes something adds one to the count. Since every clear removes blocks, the rounds cannot go on forever.
Easy to check, hard to play
The best-known ancestor of falling-block puzzles is Tetris, created by Alexey Pajitnov in the Soviet Union in the mid-1980s. Accounts differ between 1984 and 1985, and the official anniversary is June 1984. He was a researcher at the computing center of the Academy of Sciences in Moscow, and he wrote the first version in his spare time on an Elektronika 60, a computer with no graphics at all, drawing the pieces with brackets and spaces. The spark was a puzzle he had bought made of pieces of five joined squares; he cut them down to four. The name joins "tetra," Greek for four, with his favorite sport, tennis. The game spread across borders, and in 1989 a version for a handheld game console was played all over the world. A formal agreement to license the game from Pajitnov himself came only in 1996. Then in 1991 a falling-block puzzle appeared in Japan in which pairs of blobs fall, four of one color touching vanish, and chain reactions are the whole point; it started a genre of its own.
Here is a twist. Checking connections is easy, but playing well is not. In 2003 researchers at MIT showed that for that same Tetris, finding the best placements is NP-complete, meaning probably not solvable quickly, even if you know every piece that is coming. Examining a board and planning ahead are completely different kinds of difficulty.
From the pores of coal to phase transitions
In physics, Simon Broadbent and John Hammersley founded percolation theory in 1957, and by the usual account it started with coal. Coal had been a strategic material in the Second World War, not least as the main ingredient of gas masks, and in the mid-1950s Broadbent, a statistician at the British Coal Utilisation Research Association, was studying how gases and other fluids work their way through the maze of tiny pores in coal, the problem at the heart of a gas mask. In 1954 he is said to have asked Hammersley about a model of a random maze of open and closed tunnels, and the title of their first paper includes the words "crystals and mazes." Fun fact: Rosalind Franklin, later famous for her X-ray photographs of DNA, had worked at the same association during the war, on the pores of coal.
The link to phase transitions is a lovely one. Fill a square grid at random, each square with probability . Around , a giant cluster spanning the whole grid suddenly appears: one of the simplest examples of a phase transition, like water freezing. Nobody has a formula for that number; it is known to be about 0.5927 only from computer simulations that count clusters over and over, and at the heart of those simulations is the same flood fill you see here.
Percolation theory has also traveled far from coal. When animals' habitats are broken into fragments by development, ecologists use the same ideas to ask whether connected routes still remain for them to move along.
Try it on the board
- Predict first: if the pair hovering over the opening board, red below and blue above, is dropped, how many chains will follow? Then press 🔗 Watch the chain example at the top of the panel. The numbers on the blocks show the order in which they were examined.
- Under Flood-fill method, switch from BFS to Depth-first search, DFS (stack) and press 🔗 Watch the chain example again. How do the numbering and the Cells waiting row on the right differ?
- Turn on Pause between stages and step through with Next stage. At which stage does the chain counter go up?
- Set Blocks needed to clear to 3. What happens to the opening board?
- Under Edit the board, turn on Edit, tap cells to place blocks, build a 2-chain, and test it with Run chains on this board.
- On the right, compare Neighbor checks with the For comparison count, which compares every pair. How does the gap grow with more blocks?
- Press Start a game to play. Keys: ← → move, ↑ or X rotates clockwise to the right, Z rotates counterclockwise to the left, ↓ drops to the bottom.
Two honest notes: the group search is slowed down so your eyes can follow it; the real check is instant. And the score uses this simulation's own simple rule, not that of any commercial game: blocks cleared × 10 × chain number.
The programming toolkit of Informatics I is all packed into this little game: two-dimensional arrays, queues and stacks, loops and conditions, and a simulation that updates its state step by step. Write it yourself and you can experiment at once: what if three blocks were enough, or diagonal neighbors counted?
Big tools inside a little game
To a computer, the board is a table of numbers, and "connected" is something it must work out step by step. Flood fill spreads from a square to its unmarked same-colored neighbors; with a queue it is BFS, with a stack DFS, and both find the same groups. Its work grows in proportion to the number of blocks, unlike comparing every pair, and processing blocks in the wrong order when they fall leaves gaps and wrong answers.
The ideas of a 19th-century engineer marking his way through mazes and of a statistician studying the coal in gas masks now run every second inside drawing apps, text readers and this little game. A question to take away: after each landing, the program re-examines the whole board. Which part of the board really needs re-examining?
Sources and further reading
The facts in this article were checked mainly against the following.
- E. D. Demaine, S. Hohenberger and D. Liben-Nowell, "Tetris is Hard, Even to Approximate," 2003 (arXiv): finding the best placements is NP-complete
- É. Lucas, Récréations mathématiques, the chapter on labyrinths (English translation of the second edition by M. Behrend): the method "communicated to us by M. Trémaux," a former student of the École Polytechnique and telegraph engineer
- A. Rosenfeld and J. L. Pfaltz, "Sequential Operations in Digital Picture Processing," Journal of the ACM, 1966: labeling connected components in pictures
- S. R. Broadbent and J. M. Hammersley, "Percolation processes I. Crystals and mazes," Proceedings of the Cambridge Philosophical Society, 1957
- M. E. J. Newman and R. M. Ziff, "Efficient Monte Carlo Algorithm and High-Precision Results for Percolation," Physical Review Letters, 2000: the square-lattice threshold 0.59274621 from simulation
Further reading (encyclopedias):
- Wikipedia, "Tetris": Pajitnov, the Elektronika 60, the origin of the name, the 1996 agreement
- Wikipedia, "Maze-solving algorithm": Trémaux's method
- Wikipedia, "Breadth-first search": Moore's 1959 maze method
- Wikipedia, "Flood fill"
- Wikipedia, "Connected-component labeling"
- Wikipedia, "Percolation theory": BCURA and gas masks, Broadbent and Hammersley, Rosalind Franklin