Check if Move Is Legal

Medium Topics Company Tags

An 8 by 8 board contains empty cells (.), black pieces (B), and white pieces (W). You want to place a piece of color in the empty cell [rMove, cMove].

The move is legal if, starting at the new piece and following one of the eight horizontal, vertical, or diagonal directions, you encounter one or more consecutive pieces of the opposite color followed immediately by an existing piece of your own color. There must be no empty cell along this line.

The new piece must be an endpoint of the line, and the line must contain at least three cells in total. Return true if at least one such line exists; otherwise return false. Coordinates are zero-based.

The dashed square marks the proposed move.

Example 1:

Check if Move is Legal, example 1: illustration of the example

Input: board = [
  [".","W","B",".",".",".",".","."],
  [".",".",".",".",".",".",".","."],
  [".",".",".",".",".",".",".","."],
  [".",".",".",".",".",".",".","."],
  [".",".",".",".",".",".",".","."],
  [".",".",".",".",".",".",".","."],
  [".",".",".",".",".",".",".","."],
  [".",".",".",".",".",".",".","."]
]
rMove = 0
cMove = 0
color = "B"

Output: true

Explanation: Placing B at [0,0] creates the horizontal line B, W, B ending at [0,2]. The new piece is an endpoint and the one middle piece has the opposite color.

Example 2:

Check if Move is Legal, example 2: illustration of the example

Input: board = [
  [".",".",".",".",".",".",".","."],
  [".","B",".",".",".",".",".","."],
  [".",".","B",".",".",".",".","."],
  [".",".",".","W",".",".",".","."],
  [".",".",".",".",".",".",".","."],
  [".",".",".",".",".",".",".","."],
  [".",".",".",".",".",".",".","."],
  [".",".",".",".",".",".",".","."]
]
rMove = 0
cMove = 0
color = "W"

Output: true

Explanation: Placing W at [0,0] creates a diagonal line through [1,1] and [2,2] to the W at [3,3]. Both middle pieces are B, so the move is legal.

Example 3:

Check if Move is Legal, example 3: illustration of the example

Input: board = [
  [".","B",".",".",".",".",".","."],
  [".",".",".",".",".",".",".","."],
  [".",".",".",".",".",".",".","."],
  [".",".",".",".",".",".",".","."],
  [".",".",".",".",".",".",".","."],
  [".",".",".",".",".",".",".","."],
  [".",".",".",".",".",".",".","."],
  [".",".",".",".",".",".",".","."]
]
rMove = 0
cMove = 0
color = "B"

Output: false

Explanation: The neighboring B has the same color as the new piece. No opposite-color piece lies between two B endpoints, and every other direction is empty, so the move is illegal.

Constraints:

  • board has exactly 8 rows and 8 columns.
  • Each cell is ., B, or W.
  • 0 <= rMove, cMove < 8
  • board[rMove][cMove] == "."
  • color is B or W.


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.