Design Tic-Tac-Toe
Description
null
Solution(javascript)
// /**
// * Initialize your data structure here.
// * @param {number} n
// */
// const TicTacToe = function (n) {
// this.arr = new Array(n).fill(0).map(() => [])
// this.size = n
// }
// /** O(N)
// * 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.
// * @param {number} row
// * @param {number} col
// * @param {number} player
// * @return {number}
// */
// TicTacToe.prototype.move = function (row, col, player) {
// this.arr[row][col] = player
// const matrix = this.arr
// let rowWin = true
// let columnWin = true
// let cross1Win = true
// let cross2Win = true
// for (let i = 0; i < this.size; i++) {
// if (matrix[row][i] !== player) {
// rowWin = false
// }
// if (matrix[i][col] !== player) {
// columnWin = false
// }
// if (matrix[i][i] !== player) {
// cross1Win = false
// }
// if (matrix[this.size - i - 1][i] !== player) {
// cross2Win = false
// }
// }
// if (rowWin || columnWin || cross1Win || cross2Win) {
// return player
// }
// return 0
// }
/**
* Initialize your data structure here.
* @param {number} n
*/
const TicTacToe = function (n) {
this.rowSum = new Array(n).fill(0)
this.columnSum = new Array(n).fill(0)
this.cross1Sum = 0
this.cross2Sum = 0
this.size = n
}
/** O(N)
* 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.
* @param {number} row
* @param {number} col
* @param {number} player
* @return {number}
*/
TicTacToe.prototype.move = function (row, col, player) {
const origin = player
player = player === 2 ? -1 : 1
this.rowSum[row] += player
this.columnSum[col] += player
if (row === col) {
this.cross1Sum += player
}
if (row + col === this.size - 1) {
this.cross2Sum += player
}
const target = this.size * player
if (this.rowSum[row] === target
|| this.columnSum[col] === target
|| this.cross1Sum === target
|| this.cross2Sum === target) {
return origin
}
return 0
}