Workshop › Puzzle Bobble-style Bubble Shooter › Step 17 of 31

Flood fill

What we are doing

connected finds every cell reachable from a start through neighbours that pass a test, like paint spreading: a queue of cells to visit and a set of cells already seen.

```js
// Flood fill: every cell connected to (r, c) through neighbours that pass the test.
function connected(starts, test) {
  const seen = new Set(starts.map(([r, c]) => r * COLS + c))
  const queue = [...starts]
  while (queue.length) {
    const [r, c] = queue.shift()
    for (const [nr, nc] of neighbors(r, c)) {
      if (seen.has(nr * COLS + nc) || !test(nr, nc)) continue
      seen.add(nr * COLS + nc)
      queue.push([nr, nc])
    }
  }
  return [...seen].map((k) => [Math.floor(k / COLS), k % COLS])
}
```

What it means

Your turn

Under snap, write the comment and connected.

Skills: Loops, Arrays and objects

All steps

  1. The night sky
  2. One bubble
  3. A grid of cells
  4. Draw the grid
  5. Bubbles that nest
  6. The shooter
  7. Aim upwards
  8. Turn with the arrows
  9. Aim with the pointer
  10. Fire!
  11. Fly
  12. Bounce off the walls
  13. Touching something?
  14. Stick into the grid
  15. Smaller steps
  16. Six neighbours
  17. Flood fill
  18. Three in a row pop
  19. Bubbles that fall
  20. Cut them loose
  21. Show the score
  22. Only useful colors
  23. Count the shots
  24. The ceiling comes down
  25. Win or lose
  26. The danger line
  27. The end message
  28. Play again
  29. Best score
  30. A dotted guide
  31. Build it yourself: swap bubbles