Find a Go group and count its liberties with flood fill

Why it matters Liberty counting decides captures, the core rule every Go engine and self-play RL environment must get right.

Go engines and self-play agents constantly ask: which stones are connected to this one, and how many empty points touch the group?

Write group_liberties(board, r, c). board is a list of equal-length strings using "." for empty, "B" for black, "W" for white. Stones connect only up, down, left and right. If (r, c) is empty, return ([], 0). Otherwise flood fill the group of the same color containing (r, c) and return (sorted list of (row, col) tuples in the group, number of DISTINCT empty points adjacent to any stone of the group).

Signaturedef group_liberties(board, r, c)

Example

board ["BB.", "W..", "..."], r 0, c 0 gives ([(0, 0), (0, 1)], 2).

Understand the idea

In Go, stones of one color that touch up, down, left or right form a group that lives or dies together. The empty points next to a group are its liberties, its breathing room. When a group has zero liberties it is captured.

Example: board rows "BB.", "W..", "...". The black stones at (0, 0) and (0, 1) are connected. (0, 0) touches the white stone below it, so no liberty there. (0, 1) touches (0, 2) and (1, 1), both empty. The group has 2 liberties.

Rule: flood fill from the start stone over same-colored 4-neighbors; liberties = set of empty 4-neighbors of all group stones; count the set.

Every Go environment used for self-play RL, including the ones that trained AlphaGo-style agents, runs this flood fill after every move to find captures and illegal suicides.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: examplegroup_liberties(['BB.', 'W..', '...'], 0, 0)
  • Sample 2: shared libertygroup_liberties(['.B.', 'B.B', '.B.'], 0, 1)