You are given a 2D grid board representing a Go board, where each cell is one of 'B' (black stone), 'W' (white stone), or '.' (empty). You are also given two integers row and col indicating the coordinates of a specific stone on the board.
Return the number of liberties for the group of stones containing the stone at (row, col). A group consists of all stones of the same color that are connected to each other through orthogonal adjacency (up, down, left, right). The number of liberties of a group is the count of distinct empty cells ('.') that are orthogonally adjacent to any stone in that group.
Function Signature
def count_liberties(board: list[list[str]], row: int, col: int) -> int:
Rules
-
board
is a list of rows, and each row is a list of one-character strings.
(row, col)
means
board[row][col]
, with
(0, 0)
at the top left.
-
Only the four orthogonal neighbors count, both for joining stones into a group and for liberties. Diagonal cells never count, and cells off the board are not liberties.
-
An empty cell next to several stones of the group is one liberty.
Constraints
-
1 <= len(board), len(board[0]) <= 100
-
Each cell is
'B'
,
'W'
, or
'.'
-
0 <= row < len(board)
-
0 <= col < len(board[0])
-
The cell at
(row, col)
is guaranteed to be
'B'
or
'W'
Examples
Input: board = [["B","B","."],[".","B","W"],[".",".","W"]], row = 0, col = 0
Output: 3
The black group at (0, 0) contains the stones at (0, 0), (0, 1) and (1, 1). Their empty orthogonal neighbors are (0, 2), (1, 0) and (2, 1), giving 3 liberties.
Input: board = [["W","B","."],["B",".","B"],[".","B","W"]], row = 0, col = 0
Output: 0
The white stone at (0, 0) is alone in its group. Its orthogonal neighbors (0, 1) and (1, 0) are both black stones, so the group has no liberties.
Input: board = [["B",".","B"],["B","B","W"],[".","W","."]], row = 0, col = 0
Output: 2
The group is (0, 0), (1, 0) and (1, 1). The empty cell (0, 1) touches both (0, 0) and (1, 1) but counts once, and (2, 0) touches (1, 0). The black stone at (0, 2) is a separate group because its only stone neighbor is white, and the empty cell (2, 2) touches no stone of the group.