Skip to content

Commit aff1cd6

Browse files
authored
Create check-if-move-is-legal.py
1 parent 71f493e commit aff1cd6

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

Python/check-if-move-is-legal.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# Time: O(8 * n) = O(1), grid is a n x n board and n = 8
2+
# Space: O(1)
3+
4+
class Solution(object):
5+
def checkMove(self, board, rMove, cMove, color):
6+
"""
7+
:type board: List[List[str]]
8+
:type rMove: int
9+
:type cMove: int
10+
:type color: str
11+
:rtype: bool
12+
"""
13+
def check(board, color, r, c, dr, dc):
14+
l = 2
15+
while 0 <= r < len(board) and 0 <= c < len(board[0]) and board[r][c] != '.':
16+
if board[r][c] == color:
17+
return l >= 3
18+
r += dr
19+
c += dc
20+
l += 1
21+
return False
22+
23+
directions = [(0, -1), (0, 1), (-1, 0), (1, 0),
24+
(-1, -1), (1, -1), (-1, 1), (1, 1)]
25+
for dr, dc in directions:
26+
r, c = rMove+dr, cMove+dc
27+
if check(board, color, r, c, dr, dc):
28+
return True
29+
return False

0 commit comments

Comments
 (0)