Design Tic-Tac-Toe
Problem: Design Tic-Tac-Toe
We can store the sum of each row and each col as well as sum of elements on diagonal and anti-diagonal line. If player one makes a move at a position, we add one onto the sums related to that position. If player two makes a move, we add -1. In this way, we tell the results easily.
Code in Python:
class TicTacToe(object):
def __init__(self, n):
"""
Initialize your data structure here.
:type n: int
"""
self.rows = [0] * n
self.cols = [0] * n
self.diagonal = 0
self.antidiagonal = 0
self.n = n
def move(self, row, col, player):
"""
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.
:type row: int
:type col: int
:type player: int
:rtype: int
"""
n = self.n
p = 1 if player == 2 else -1
self.rows[row] += p
self.cols[col] += p
if row == col : self.diagonal += p
if row + col == n - 1 : self.antidiagonal += p
if self.rows[row] == n or self.cols[col] == n or self.diagonal == n or self.antidiagonal == n:
return 2
elif self.rows[row] == -n or self.cols[col] == -n or self.diagonal == -n or self.antidiagonal == -n:
return 1
else:
return 0
# Your TicTacToe object will be instantiated and called as such:
# obj = TicTacToe(n)
# param_1 = obj.move(row,col,player)