*348 Design Tic-Tac-Toe

https://leetcode.com/problems/design-tic-tac-toe/

solution

class TicTacToe(object):
    def __init__(self, n):
        self.n = n
        self.row = [0] * n  # 记录下,每一行的和,每一列的和,两个对角线的和
        self.col = [0] * n
        self.left = 0
        self.right = 0

    def move(self, row, col, player):
        if player == 1:
            delta = 1
        else:
            delta = -1

        self.row[row] += delta
        self.col[col] += delta
        if row == col:
            self.left += delta
        if row == self.n - 1 - col:
            self.right += delta

        # 每一个条件判断也可以在各自加delta之后立马判断
        if abs(self.row[row]) == self.n or abs(self.col[col]) == self.n or abs(self.left) == self.n or abs(self.right) == self.n:
            return player

        return 0

时间复杂度:O() 空间复杂度:O()

follow up

794. Valid Tic-Tac-Toe State

Last updated