Design Tic-Tac-Toe

Assume the following rules are for the tic-tac-toe game on an n x n board between two players:

Design Tic-Tac-Toe

Assume the following rules are for the tic-tac-toe game on an n x n board between two players:

  1. A move is guaranteed to be valid and is placed on an empty block.
  2. Once a winning condition is reached, no more moves are allowed.
  3. A player who succeeds in placing n of their marks in a horizontal, vertical, or diagonal row wins the game.

Implement the TicTacToe class:

  • TicTacToe(int n) Initializes the object the size of the board n.
  • int move(int row, int col, int player) Indicates that player with id player plays at the cell (row, col)of the board. The move is guaranteed to be a valid move.

Follow up:
Could you do better than O(n2) per move() operation?

Constraints:

  • 2 <= n <= 100
  • player is 1 or 2.
  • 1 <= row, col <= n
  • (row, col) are unique for each different call to move.
  • At most n2 calls will be made to move.

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

Solution

class TicTacToe {
var rows: [Int]!
var cols: [Int]!
var diagonal: Int!
var antiDiagonal: Int!
/** Initialize your data structure here. */
init(_ n: Int) {
rows = []
cols = []
for i in 0..<n {
rows.append(0)
cols.append(0)
}
diagonal = 0
antiDiagonal = 0
}
/** 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. */
func move(_ row: Int, _ col: Int, _ player: Int) -> Int {
let toAdd = player == 1 ? 1 : -1
rows[row] = rows[row] + toAdd
cols[col] = cols[col] + toAdd
if row == col {
diagonal += toAdd
}
if col == (cols.count - row - 1){
antiDiagonal += toAdd
}
let size = rows.count
if abs(rows[row]) == size ||
abs(cols[col]) == size ||
abs(diagonal) == size ||
abs(antiDiagonal) == size {
return player;
}
return 0
}
}
/**
* Your TicTacToe object will be instantiated and called as such:
* let obj = TicTacToe(n)
* let ret_1: Int = obj.move(row, col, player)
*/
view raw TicTacToe.swift hosted with ❤ by GitHub