Python O(1) Time for Move, Performance increases toward the end


  • 0
    X
    class TicTacToe(object):
    
        def __init__(self, n):
            
            self.n = n
            
            self.rows = {}
            for i in range(n):
                self.rows[i] = [0,0]
                
            self.cols = {}
            for i in range(n):
                self.cols[i] = [0,0]
                
            self.diag = {}
            self.diag[0] = [0,0]
            self.diag[1] = [0,0]
    
        def move(self, row, col, player):
            
            playerIndex = player - 1
            
            def update(playerTuple):
                playerTuple[playerIndex]+=1
                won = playerTuple[playerIndex] == self.n
                if 0 not in playerTuple:
                    del playerTuple
                return won
                
            if row in self.rows:
                if update(self.rows[row]):
                    return player
                
            if col in self.cols:
                if update(self.cols[col]):
                    return player
                    
            if row == col and 0 in self.diag:
                if update(self.diag[0]):
                    return player
            
            if row + col == self.n-1 and 1 in self.diag:
                if update(self.diag[1]):
                    return player
                
            return 0
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.