# LeetCode: 1275. 找出井字棋的获胜者¶

## 1、题目描述¶

AB 在一个 3 x 3 的网格上玩井字棋。

• 玩家轮流将棋子放在空方格 (" ") 上。
• 第一个玩家 A 总是用 "X" 作为棋子，而第二个玩家 B 总是用 "O" 作为棋子。
• "X""O" 只能放在空方格中，而不能放在已经被占用的方格上。
• 只要有 3 个相同的（非空）棋子排成一条直线（行、列、对角线）时，游戏结束。
• 如果所有方块都放满棋子（不为空），游戏也会结束。
• 游戏结束后，棋子无法再进行任何移动。

输入：moves = [[0,0],[2,0],[1,1],[2,1],[2,2]]

"X  "    "X  "    "X  "    "X  "    "X  "
"   " -> "   " -> " X " -> " X " -> " X "
"   "    "O  "    "O  "    "OO "    "OOX"


输入：moves = [[0,0],[1,1],[0,1],[0,2],[1,0],[2,0]]

"X  "    "X  "    "XX "    "XXO"    "XXO"    "XXO"
"   " -> " O " -> " O " -> " O " -> "XO " -> "XO "
"   "    "   "    "   "    "   "    "   "    "O  "


输入：moves = [[0,0],[1,1],[2,0],[1,0],[1,2],[2,1],[0,1],[0,2],[2,2]]

"XXO"
"OOX"
"XOX"


输入：moves = [[0,0],[1,1]]

"X  "
" O "
"   "


• $1 <= moves.length <= 9$
• $moves[i].length == 2$
• $0 <= moves[i][j] <= 2$
• moves 里没有重复的元素。
• moves 遵循井字棋的规则。

## 2、解题思路¶

• a的标记为1b的标记为-1
• 当找到直线之和为3或者-3，返回结果
class Solution:
def tictactoe(self, moves: List[List[int]]) -> str:
def check(desk):

for i in range(3):
if sum(desk[i]) == 3:
return "A"
elif sum(desk[i]) == -3:
return "B"
for j in range(3):
cur = sum([desk[i][j] for i in range(3)])
if cur == 3:
return "A"
elif cur == -3:
return "B"
left_right = sum([desk[0][0], desk[1][1], desk[2][2]])
right_left = sum([desk[0][2], desk[1][1], desk[2][0]])
if left_right == 3 or right_left == 3:
return "A"
if left_right == -3 or right_left == -3:
return "B"
return "C"

d = [[0 for _ in range(3)] for _ in range(3)]
length = len(moves)
for index, (x, y) in enumerate(moves):
if index % 2 == 0:
d[x][y] = 1
else:
d[x][y] = -1
cur = check(d)
if cur != "C":
return cur
if length == 9:
return "Draw"
else:
return "Pending"