pretty simple naive way


  • 0

    I think this solution first came out my mind, so when we try to solve a problem, try all you can!

    class TicTacToe(object):
    
        def __init__(self, n):
            self.grid=[[0 for _ in xrange(n)] for _ in xrange(n)]
            self.size=n
    
        def move(self, row, col, player):
            if row<0 or row>=self.size or col<0 or col>=self.size:
                return -1
                
            self.grid[row][col]=player
            
            # column
            i=0
            while i<self.size:
                if self.grid[row][i]==player:
                    i+=1
                else:
                    break
            if i==self.size:
                return player
            
            # row
            i=0
            while i<self.size:
                if self.grid[i][col]==player:
                    i+=1
                else:
                    break
            if i==self.size:
                return player
            
            # diagonal
            if row==col:
                i=0
                while i<self.size:
                    if self.grid[i][i]==player:
                        i+=1
                    else:
                        break
                if i==self.size:
                    return player
            
            # reverse diagonal     
            if row+col==self.size-1: 
                i=0
                while i<self.size:
                    if self.grid[i][self.size-i-1]==player:
                        i+=1
                    else:
                        break
                if i==self.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.