Check if Move is Legal - Problem

You are given a 0-indexed 8 x 8 grid board, where board[r][c] represents the cell (r, c) on a game board. On the board, free cells are represented by '.', white cells are represented by 'W', and black cells are represented by 'B'.

Each move in this game consists of choosing a free cell and changing it to the color you are playing as (either white or black). However, a move is only legal if, after changing it, the cell becomes the endpoint of a good line (horizontal, vertical, or diagonal).

A good line is a line of three or more cells (including the endpoints) where:

  • The endpoints of the line are one color
  • The remaining cells in the middle are the opposite color
  • No cells in the line are free

Given two integers rMove and cMove and a character color representing the color you are playing as ('W' for white or 'B' for black), return true if changing cell (rMove, cMove) to color is a legal move, or false if it is not legal.

Input & Output

Example 1 — Valid Black Move
$ Input: board = [[".",".",".","B",".",".",".","."],[".",".",".","W",".",".",".","."],[".",".",".","W",".",".",".","."],[".",".",".","W",".",".",".","."],...], rMove = 4, cMove = 3, color = "B"
Output: true
💡 Note: Placing 'B' at (4,3) creates a good line vertically: B at (0,3) -> W at (1,3), W at (2,3), W at (3,3) -> B at (4,3)
Example 2 — Invalid Move on Occupied Cell
$ Input: board = [[".",".",".",".",".",".",".","."],[".","B",".",".",".",".",".","."],[".",".","W",".",".",".",".","."],[".",".",".","W",".",".",".","."],...], rMove = 1, cMove = 1, color = "B"
Output: false
💡 Note: Cell (1,1) is already occupied by 'B', so the move is illegal
Example 3 — No Valid Line Formation
$ Input: board = [[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."],...], rMove = 0, cMove = 0, color = "W"
Output: false
💡 Note: Placing 'W' at (0,0) doesn't create any good line since there are no other pieces on the board

Constraints

  • board.length == 8
  • board[i].length == 8
  • 0 ≤ rMove, cMove < 8
  • board[rMove][cMove] == '.'
  • color is either 'W' or 'B'

Visualization

Tap to expand
Check if Move is Legal: Good Line ValidationInput BoardBWW?Place B at (0,3)Check 8 DirectionsResultBWWBGood Line Found!Pattern: B-W-W-B forms a valid line horizontallyOutput: true
Understanding the Visualization
1
Input
8x8 board with W/B/. cells, target position and color
2
Process
Check 8 directions for good lines (same-opposite-same pattern)
3
Output
true if at least one good line exists, false otherwise
Key Takeaway
🎯 Key Insight: A move is legal if it creates at least one good line in any direction
Asked in
Google 15 Microsoft 12 Amazon 8
15.2K Views
Medium Frequency
~25 min Avg. Time
485 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen