Check if Move is Legal — LeetCode 1958 Python Solution
- Problem
- #1958
- Pattern
- Matrix and Grid
- Reading time
- 3 min
- Source
- leetcode.com
The 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'.
Example
- Input
- board = [[".",".",".","B",".",".",".","."],[".",".",".","W",".",".",".","."],[".",".",".","W",".",".",".","."],[".",".",".","W",".",".",".","."],["W","B","B",".","W","W","W","B"],[".",".",".","B",".",".",".","."],[".",".",".","B",".",".",".","."],[".",".",".","W",".",".",".","."]], rMove = 4, cMove = 3, color = "B"
- Output
- true
- Explanation
- '.', 'W', and 'B' are represented by the colors blue, white, and black respectively, and cell (rMove, cMove) is marked with an 'X'.
Python solution
class Solution:
def checkMove(
self, board: List[List[str]], rMove: int, cMove: int, color: str
) -> bool:
for a in range(-1, 2):
for b in range(-1, 2):
if a == 0 and b == 0:
continue
i, j = rMove, cMove
cnt = 0
while 0 <= i + a < 8 and 0 <= j + b < 8:
cnt += 1
i, j = i + a, j + b
if cnt > 1 and board[i][j] == color:
return True
if board[i][j] in (color, "."):
break
return FalseComplexity
| Measure | Complexity |
|---|---|
| Time | O(m + n), where m is the number of rows and n is the number of columns in \textit{board}, with m = n = 8 in this problem |
| Space | O(1) auxiliary |
Pattern: Matrix and Grid
Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 1958. Check if Move is Legal is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Matrix.
The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1958. Check if Move is Legal?
- LeetCode 1958. Check if Move is Legal is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1958. Check if Move is Legal?
- The Python solution on this page runs in O(m + n), where m is the number of rows and n is the number of columns in \textit{board}, with m = n = 8 in this problem.
- What is the space complexity of LeetCode 1958. Check if Move is Legal?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 1958. Check if Move is Legal cover?
- LeetCode 1958. Check if Move is Legal is tagged Array, Enumeration and Matrix on LeetCode.