|
| 1 | +/** |
| 2 | + * 348. Design Tic-Tac-Toe |
| 3 | + * https://leetcode.com/problems/design-tic-tac-toe/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Assume the following rules are for the tic-tac-toe game on an n x n board between two players: |
| 7 | + * 1. A move is guaranteed to be valid and is placed on an empty block. |
| 8 | + * 2. Once a winning condition is reached, no more moves are allowed. |
| 9 | + * 3. A player who succeeds in placing n of their marks in a horizontal, vertical, or diagonal |
| 10 | + * row wins the game. |
| 11 | + * |
| 12 | + * Implement the TicTacToe class: |
| 13 | + * - TicTacToe(int n) Initializes the object the size of the board n. |
| 14 | + * - int move(int row, int col, int player) Indicates that the player with id player plays at the |
| 15 | + * cell (row, col) of the board. The move is guaranteed to be a valid move, and the two players |
| 16 | + * alternate in making moves. Return |
| 17 | + * - 0 if there is no winner after the move, |
| 18 | + * - 1 if player 1 is the winner after the move, or |
| 19 | + * - 2 if player 2 is the winner after the move. |
| 20 | + */ |
| 21 | + |
| 22 | +/** |
| 23 | + * @param {number} n |
| 24 | + */ |
| 25 | +var TicTacToe = function(n) { |
| 26 | + this.size = n; |
| 27 | + this.rows = new Array(n).fill(0); |
| 28 | + this.cols = new Array(n).fill(0); |
| 29 | + this.diagonal = 0; |
| 30 | + this.antiDiagonal = 0; |
| 31 | +}; |
| 32 | + |
| 33 | +/** |
| 34 | + * @param {number} row |
| 35 | + * @param {number} col |
| 36 | + * @param {number} player |
| 37 | + * @return {number} |
| 38 | + */ |
| 39 | +TicTacToe.prototype.move = function(row, col, player) { |
| 40 | + const value = player === 1 ? 1 : -1; |
| 41 | + |
| 42 | + this.rows[row] += value; |
| 43 | + this.cols[col] += value; |
| 44 | + |
| 45 | + if (row === col) { |
| 46 | + this.diagonal += value; |
| 47 | + } |
| 48 | + |
| 49 | + if (row + col === this.size - 1) { |
| 50 | + this.antiDiagonal += value; |
| 51 | + } |
| 52 | + |
| 53 | + if (Math.abs(this.rows[row]) === this.size || Math.abs(this.cols[col]) === this.size |
| 54 | + || Math.abs(this.diagonal) === this.size || Math.abs(this.antiDiagonal) === this.size) { |
| 55 | + return player; |
| 56 | + } |
| 57 | + |
| 58 | + return 0; |
| 59 | +}; |
0 commit comments