标签:时间 tco toe not int row sum __init__ called
正确做法是: 只保存行/列/对角线的和,而不用保存所有元素,空间复杂度从O(n2)降到O(n);move()只需判断四个值是否 = n - 1: 当前行sum,当前列sum,两个对角线,时间复杂度为O(1)
而我只是用dict记录是否还有可能赢。差强人意。
class TicTacToe:
def __init__(self, n: int):
"""
Initialize your data structure here.
"""
self.board = [[0] * n for i in range(n)]
self.validRows = set([i for i in range(n)])
self.validCols = set([i for i in range(n)])
self.validCrosses = set([0, 1])
def move(self, row: int, col: int, player: int) -> int:
"""
Player {player} makes a move at ({row}, {col}).
@param row The row of the board.
@param col The column of the board.
@param player The player, can be either 1 or 2.
@return The current winning condition, can be either:
0: No one wins.
1: Player 1 wins.
2: Player 2 wins.
"""
n = len(self.board)
self.board[row][col] = player
# each row
for i in range(n):
if i not in self.validRows:
continue
cnt1 = 0
cnt2 = 0
for j in range(n):
if self.board[i][j] == 1:
cnt1 += 1
elif self.board[i][j] == 2:
cnt2 += 1
if cnt1 == n:
return 1
elif cnt2 == n:
return 2
if cnt1 > 0 and cnt2 > 0:
self.validRows.remove(i)
# each column
for i in range(n):
if i not in self.validCols:
continue
cnt1 = 0
cnt2 = 0
for j in range(n):
if self.board[j][i] == 1:
cnt1 += 1
elif self.board[j][i] == 2:
cnt2 += 1
if cnt1 == n:
return 1
elif cnt2 == n:
return 2
if cnt1 > 0 and cnt2 > 0:
self.validCols.remove(i)
# two cross
if 0 in self.validCrosses:
cnt1 = 0
cnt2 = 0
for i in range(n):
if self.board[i][i] == 1:
cnt1 += 1
elif self.board[i][i] == 2:
cnt2 += 1
if cnt1 == n:
return 1
elif cnt2 == n:
return 2
if cnt1 > 0 and cnt2 > 0:
self.validCrosses.remove(0)
if 1 in self.validCrosses:
cnt1 = 0
cnt2 = 0
for i in range(n):
if self.board[i][n-i-1] == 1:
cnt1 += 1
elif self.board[i][n-i-1] == 2:
cnt2 += 1
if cnt1 == n:
return 1
elif cnt2 == n:
return 2
if cnt1 > 0 and cnt2 > 0:
self.validCrosses.remove(1)
return 0
# Your TicTacToe object will be instantiated and called as such:
# obj = TicTacToe(n)
# param_1 = obj.move(row,col,player)
标签:时间 tco toe not int row sum __init__ called
原文地址:https://www.cnblogs.com/lautsie/p/12271195.html