Reversi move simulation with captures in 8 directions
I was asked this
No reports yet. Sign in to say where you were asked it.
Implement one move of the board game Reversi (also sold as Othello).
You get an n x n board as a list of lists of characters. Each cell is 'B' (black), 'W' (white) or '.' (empty). You also get row, col and player ('B' or 'W').
Write make_move(board, row, col, player) that returns the board after player tries to place a piece at (row, col).
Rules
- Look from
(row, col)in each of the 8 directions (horizontal, vertical, diagonal). - A direction captures when it holds one or more consecutive opponent pieces followed directly by a
playerpiece. An empty cell or the board edge before the closing piece means no capture in that direction. - If at least one direction captures, place the piece and flip every captured opponent piece in every capturing direction to
player. - If the cell is occupied, off the board, or no direction captures, the move is illegal: return the board unchanged.
- Do not modify the input board; return a new one.
Constraints
1 <= n <= 100-
playeris'B'or'W'.
Example 1
board = [".WWB",
"WW..",
"B.B.",
"...."]
row = 0, col = 0, player = 'B'
Output:
["BBBB",
"BB..",
"B.B.",
"...."]
The run to the right closes on (0, 3), the run down closes on (2, 0), and the diagonal closes on (2, 2), so all four white pieces flip.
Example 2
board = [".WW",
"...",
"..."]
row = 0, col = 0, player = 'B'
Output: the same board. The white run reaches the edge without a black piece to close it, so the move is illegal.
Reconstructed from the reported question; details may differ from what interviewers ask.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
Sign in to submit your code; every attempt is kept here.
