A 和 B 在一个 3 x 3 的网格上玩井字棋。
井字棋游戏的规则如下:
给你一个数组 moves
,其中每个元素是大小为 2
的另一个数组(元素分别对应网格的行和列),它按照 A 和 B 的行动顺序(先 A 后 B)记录了两人各自的棋子位置。
如果游戏存在获胜者(A 或 B),就返回该游戏的获胜者;如果游戏以平局结束,则返回 "Draw";如果仍会有行动(游戏未结束),则返回 "Pending"。
你可以假设 moves
都 有效(遵循井字棋规则),网格最初是空的,A 将先行动。
示例 1:
输入:moves = [[0,0],[2,0],[1,1],[2,1],[2,2]] 输出:"A" 解释:"A" 获胜,他总是先走。 "X " "X " "X " "X " "X " " " -> " " -> " X " -> " X " -> " X " " " "O " "O " "OO " "OOX"
示例 2:
输入:moves = [[0,0],[1,1],[0,1],[0,2],[1,0],[2,0]] 输出:"B" 解释:"B" 获胜。 "X " "X " "XX " "XXO" "XXO" "XXO" " " -> " O " -> " O " -> " O " -> "XO " -> "XO " " " " " " " " " " " "O "
示例 3:
输入:moves = [[0,0],[1,1],[2,0],[1,0],[1,2],[2,1],[0,1],[0,2],[2,2]] 输出:"Draw" 解释:由于没有办法再行动,游戏以平局结束。 "XXO" "OOX" "XOX"
示例 4:
输入:moves = [[0,0],[1,1]] 输出:"Pending" 解释:游戏还没有结束。 "X " " O " " "
提示:
1 <= moves.length <= 9
moves[i].length == 2
0 <= moves[i][j] <= 2
moves
里没有重复的元素。moves
遵循井字棋的规则。class Solution:
def tictactoe(self, moves: List[List[int]]) -> str:
A_moves = []
B_moves = []
i = 0
while i < len(moves):
if i % 2 == 0:
A_moves.append(moves[i])
else:
B_moves.append(moves[i])
i += 1
if [0,0] in A_moves and [1,1] in A_moves and [2,2] in A_moves :
return "A"
elif [0,2] in A_moves and [1,1] in A_moves and [2,0] in A_moves :
return "A"
elif [0,0] in B_moves and [1,1] in B_moves and [2,2] in B_moves :
return "B"
elif [0,2] in B_moves and [1,1] in B_moves and [2,0] in B_moves :
return "B"
else:
count = [0, 0, 0, 0, 0, 0]
for i in range(len(A_moves)):
for j in range(len(A_moves[i])):
if j == 0:
a = A_moves[i][0]
count[a] += 1
elif j == 1:
b = A_moves[i][j]
count[b+3] += 1
if max(count) == 3:
return "A"
else:
count = [0, 0, 0, 0, 0, 0]
for i in range(len(B_moves)):
for j in range(len(B_moves[i])):
if j == 0:
a = B_moves[i][0]
count[a] += 1
elif j == 1:
b = B_moves[i][j]
count[b+3] += 1
if max(count) == 3:
return "B"
elif len(moves)== 9:
return "Draw"
else:
return "Pending"
可以用函数化简代码。
嵌套列表的使用。
循环写法。