Ctrl K

Flanking Move on the Board

Medium
You are given an 8×8 board board for a two-colour game. Each cell board[r][c] is '.' (empty), 'W' (a white piece) or 'B' (a black piece). The player of colour color wants to place a piece on the empty cell (row, col). The move is legal only if, afterwards, that cell is an end of a *flanking line*: horizontal, vertical or diagonal. A flanking line is a run of at least three consecutive cells whose two ends are both color and whose cells in between (at least one) are all the opposite colour. A flanking line contains no empty cells. Return True if the move is legal, and False otherwise.
Example 1
board=[['.', '.', '.', '.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.', '.', '.', '.'], ['.', '.', '.', 'W', 'B', '.', '.', '.'], ['.', '.', '.', 'B', 'W', '.', '.', '.'], ['.', '.', '.', '.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.', '.', '.', '.']], row=2, col=3, color='B' → True

Going down from (2, 3): white at (3, 3), then black at (4, 3). That makes a B-W-B line, so the move is legal.

Example 2
board=[['.', '.', '.', '.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.', '.', '.', '.'], ['.', '.', '.', 'W', 'B', '.', '.', '.'], ['.', '.', '.', 'B', 'W', '.', '.', '.'], ['.', '.', '.', '.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.', '.', '.', '.']], row=2, col=3, color='W' → False

The only opposing neighbour of (2, 3) is black at (3, 4), and beyond it on that diagonal is an empty cell, so no line closes.

Constraints
  • The board is exactly 8×8, cells are '.', 'W' or 'B'
  • 0 ≤ row, col < 8
  • board[row][col] == '.'
  • color is 'B' or 'W'
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsA Word in a Crossword Slot MediumColumns That Cover Rows MediumPrimes Along Grid Rays MediumOne Repaint to a Solid Block EasyThree Rectangles Over the Ones Hard
loading Python…
Input
board=[['.', '.', '.', '.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.', '.', '.', '.'], ['.', '.', '.', 'W', 'B', '.', '.', '.'], ['.', '.', '.', 'B', 'W', '.', '.', '.'], ['.', '.', '.', '.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.', '.', '.', '.']], row=2, col=3, color='B'
Expected
True

Run checks the first 3 tests in your browser. Submit checks all 6 tests on the server, hidden ones included.