Design Tic-Tac-Toe
Design Tic-Tac-Toe
Assume the following rules are for the tic-tac-toe game on an
n x n
board
between two players:
- A move is guaranteed to be valid and is placed on an empty block.
- Once a winning condition is reached, no more moves are allowed.
-
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 boardn
. -
int move(int row, int col, int player)
Indicates that player with idplayer
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
or2
. -
1 <= row, col <= n
-
(row, col)
are unique for each different call tomove
. -
At most
n2
calls will be made tomove
.
Practise: https://leetcode.com/problems/design-tic-tac-toe/
Solution
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
*/ |