·1275 井字棋的获胜者
A 和 B 在一个 3 x 3 的网格上玩井字棋。
井字棋游戏的规则如下:
玩家轮流将棋子放在空方格 (" ") 上。
第一个玩家 A 总是用 "X" 作为棋子,而第二个玩家 B 总是用 "O" 作为棋子。
"X" 和 "O" 只能放在空方格中,而不能放在已经被占用的方格上。
只要有 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数组变成两个数组就可以看清楚每一步的步骤,然后在判断。为了方便,先定义三个子函数,分别判断对角线、横直线和竖直线中是否存在直线。if判断语句,若是在AB两个玩家中出现直线,则输出玩家昵称。若是没有直线且长度为9,说明平局;若是没有赢家,但是仍有空格说明,还没结束
·代码
class Solution(object):
def tictactoe(self, moves):
A_moves = []
B_moves = []
size = len(moves)
for i in range(0,size,2):
A_moves.append(moves[i])
for i in range(1,size,2):
B_moves.append(moves[i])
def Diagonal(moves):
if [0,2] in moves and [1,1] in moves and [2,0] in moves or [0,0] in moves and [1,1] in moves and [2,2] in moves:
return True
else:
return False
def Horizontal(moves):
for row in range(3):
if [row, 0] in moves and [row, 1] in moves and [row, 2] in moves:
return True
return False
def Vertical(moves):
for col in range(3):
if [0, col] in moves and [1, col] in moves and [2, col] in moves:
return True
return False
if Diagonal(A_moves) or Horizontal(A_moves) or Vertical(A_moves):
return 'A'
elif Diagonal(B_moves) or Horizontal(B_moves) or Vertical(B_moves):
return 'B'
elif size == 9 :
return 'Draw'
else:
return "Pending"