1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
|
class Solution:
def is_king_in_check(self, board: List[str]) -> bool:
king_row, king_col = -1, -1
# Find king position
for i in range(8):
for j in range(8):
if board[i][j] == 'K':
king_row, king_col = i, j
break
if king_row != -1:
break
# Check if any white piece attacks the king
for i in range(8):
for j in range(8):
piece = board[i][j]
if piece != '.' and piece != 'K':
if self._can_attack(board, i, j, king_row, king_col, piece):
return True
return False
def _can_attack(self, board: List[str], piece_row: int, piece_col: int,
king_row: int, king_col: int, piece: str) -> bool:
if piece == 'Q':
return self._can_queen_attack(board, piece_row, piece_col, king_row, king_col)
elif piece == 'R':
return self._can_rook_attack(board, piece_row, piece_col, king_row, king_col)
elif piece == 'B':
return self._can_bishop_attack(board, piece_row, piece_col, king_row, king_col)
elif piece == 'N':
return self._can_knight_attack(piece_row, piece_col, king_row, king_col)
elif piece == 'P':
return self._can_pawn_attack(piece_row, piece_col, king_row, king_col)
return False
def _can_queen_attack(self, board: List[str], r1: int, c1: int, r2: int, c2: int) -> bool:
return (self._can_rook_attack(board, r1, c1, r2, c2) or
self._can_bishop_attack(board, r1, c1, r2, c2))
def _can_rook_attack(self, board: List[str], r1: int, c1: int, r2: int, c2: int) -> bool:
if r1 != r2 and c1 != c2:
return False
return self._has_clear_path(board, r1, c1, r2, c2)
def _can_bishop_attack(self, board: List[str], r1: int, c1: int, r2: int, c2: int) -> bool:
if abs(r1 - r2) != abs(c1 - c2):
return False
return self._has_clear_path(board, r1, c1, r2, c2)
def _can_knight_attack(self, r1: int, c1: int, r2: int, c2: int) -> bool:
dr, dc = abs(r1 - r2), abs(c1 - c2)
return (dr == 2 and dc == 1) or (dr == 1 and dc == 2)
def _can_pawn_attack(self, r1: int, c1: int, r2: int, c2: int) -> bool:
return r1 + 1 == r2 and abs(c1 - c2) == 1
def _has_clear_path(self, board: List[str], r1: int, c1: int, r2: int, c2: int) -> bool:
dr = 0 if r2 - r1 == 0 else (r2 - r1) // abs(r2 - r1)
dc = 0 if c2 - c1 == 0 else (c2 - c1) // abs(c2 - c1)
r, c = r1 + dr, c1 + dc
while r != r2 or c != c2:
if board[r][c] != '.':
return False
r += dr
c += dc
return True
|