call(back)
Algorithms & Data StructuresmediumSign in to star problems

Capture Stones on a Go Board

A Go board is a grid of 'e' (empty), 'b' (black) and 'w' (white). After me plays a stone at (row, col), how many foe stones are captured? A group of same-coloured, four-directionally connected stones is captured when it has no adjacent empty point after the move. Only enemy groups touching the placed stone can be affected. Return -1 if the point is occupied.

board = ["ebe",
         "bwe",
         "ebe"]
captureStones(board, 1, 2, "b", "w")  ->  1     // the white stone loses its last liberty

Hints

Hint 1

Place the stone in a copy of the board, then for each of its four neighbours that holds an enemy stone not yet examined, flood-fill that group, collecting its stones and noting whether any neighbour of the group is empty.

Hint 2

A group with no empty neighbour is captured: add its size. Track examined stones across groups so a group touching the placed stone on two sides is counted once.

Asked at