Check if Move is Legal

This problem can be approached by checking in all eight directions from the given cell (rMove, cMove). If we find a line that fulfills the criteria of a ‘good line’ as specified in the problem statement, we return True.

Python solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution:
    def checkMove(self, board: List[List[str]], rMove: int, cMove: int, color: str) -> bool:
        dirs = [(0, 1), (1, 0), (0, -1), (-1, 0), (1, 1), (-1, -1), (1, -1), (-1, 1)]
        opposite_color = 'B' if color == 'W' else 'W'

        for dx, dy in dirs:
            x, y = rMove + dx, cMove + dy
            if 0 <= x < 8 and 0 <= y < 8 and board[x][y] == opposite_color:
                while 0 <= x + dx < 8 and 0 <= y + dy < 8:
                    x += dx
                    y += dy
                    if board[x][y] == color:
                        return True
                    elif board[x][y] == '.':
                        break

        return False

In the code above:

  • dirs is a list of eight directions. Each direction is represented by a pair of integers.
  • opposite_color is the opposite color of color.
  • For each direction, we first move one step from (rMove, cMove) to (x, y). If (x, y) is inside the board and its color is opposite_color, we continue moving in the same direction.
  • During the movement, if we find a cell with color color, we return True. If we find a cell that is free, we break the loop and continue with the next direction.
  • If we don’t find any good line in all eight directions, we return False.