progress

~/problems / Graphs / BFS / multi-source BFS

Score a tile-laying board

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min Airbnb

In a tile-laying board game, each square holds two characters: an uppercase land letter (F forest, W water, G grass, ...) and a digit 0-9, the crowns on that square. ".." is an empty square.

Squares with the same letter that touch up, down, left or right form a territory, worth

(number of squares in it) x (total crowns on its squares)

Write board_score(board: list[list[str]]) -> int: the sum over all territories. Empty squares never count.

board = [
    ["F1", "F0", "W0"],
    ["G0", "F2", "W1"],
    ["G1", "G0", ".."],
]
board_score(board)   # 14
# forest {(0,0),(0,1),(1,1)}: 3 squares x 3 crowns = 9
# water  {(0,2),(1,2)}:       2 squares x 1 crown  = 2
# grass  {(1,0),(2,0),(2,1)}: 3 squares x 1 crown  = 3
  • Separate territories with the same letter score separately: [["F1", "W0", "F1"]] scores 2.
  • Don't modify board.

⭐ Bonus: a speed test on a 500 x 500 board (one territory covers it all) earns a star if you visit each square once without recursion (Python's limit is about 1,000 frames).

Show hint

Flood-fill each territory once, tracking its size and crowns as you go.

Topic: BFS / multi-source BFS. Level-by-level search; seed the queue with every source.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc