Golang solution O(1) time


  • 0
    R
    type TicTacToe struct {
        rows []int
        cols []int
        diagonal int
        antiDiagonal int    
    }
    
    func Constructor(n int) TicTacToe {
        a:= TicTacToe{}
        a.rows = make([]int, n)
        a.cols = make([]int, n)
        a.diagonal = 0
        a.antiDiagonal = 0
    
        for i:=0; i < n; i++ {
            a.rows[i] = 0
            a.cols[i] = 0
        }
        return a
        
    }
    
    func (this *TicTacToe) Move(row int, col int, player int) int {
        toAdd := 0
        if player == 1 {
            toAdd = 1
        } else {
            toAdd = -1
        }
    
        this.rows[row] += toAdd
        this.cols[col] += toAdd
    
        if row == col {
            this.diagonal += toAdd
        }
        
        if col == (len(this.cols) - row - 1) {
            this.antiDiagonal += toAdd
        }
        
        size:= len(this.rows)
        
        e := this.rows[row]
        if this.rows[row] < 0 {
            e = -e
        }
        f := this.cols[col] 
        if f < 0 {
            f = -f
        }
        
        g := this.diagonal
        if this.diagonal < 0 {
            g = -g
        }
        
        h := this.antiDiagonal
        if this.antiDiagonal < 0 {
            h = -h
        }
        
        
        if e == size || f == size ||  g == size || h == size {
            
            return player
        }
        
        return 0
    }
    

Log in to reply
 

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