|
| 1 | +/** |
| 2 | + * 794. Valid Tic-Tac-Toe State |
| 3 | + * https://leetcode.com/problems/valid-tic-tac-toe-state/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Given a Tic-Tac-Toe board as a string array board, return true if and only if it is possible |
| 7 | + * to reach this board position during the course of a valid tic-tac-toe game. |
| 8 | + * |
| 9 | + * The board is a 3 x 3 array that consists of characters ' ', 'X', and 'O'. The ' ' character |
| 10 | + * represents an empty square. |
| 11 | + * |
| 12 | + * Here are the rules of Tic-Tac-Toe: |
| 13 | + * - Players take turns placing characters into empty squares ' '. |
| 14 | + * - The first player always places 'X' characters, while the second player always places 'O' |
| 15 | + * characters. |
| 16 | + * - 'X' and 'O' characters are always placed into empty squares, never filled ones. |
| 17 | + * - The game ends when there are three of the same (non-empty) character filling any row, |
| 18 | + * column, or diagonal. |
| 19 | + * - The game also ends if all squares are non-empty. |
| 20 | + * - No more moves can be played if the game is over. |
| 21 | + */ |
| 22 | + |
| 23 | +/** |
| 24 | + * @param {string[]} board |
| 25 | + * @return {boolean} |
| 26 | + */ |
| 27 | +var validTicTacToe = function(board) { |
| 28 | + let xCount = 0; |
| 29 | + let oCount = 0; |
| 30 | + |
| 31 | + for (const row of board) { |
| 32 | + for (const cell of row) { |
| 33 | + if (cell === 'X') xCount++; |
| 34 | + if (cell === 'O') oCount++; |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + if (xCount !== oCount && xCount !== oCount + 1) return false; |
| 39 | + |
| 40 | + const hasWon = player => { |
| 41 | + for (let i = 0; i < 3; i++) { |
| 42 | + if (board[i] === player.repeat(3)) return true; |
| 43 | + if (board[0][i] === player && board[1][i] === player && board[2][i] === player) return true; |
| 44 | + } |
| 45 | + |
| 46 | + return (board[0][0] === player && board[1][1] === player && board[2][2] === player) |
| 47 | + || (board[0][2] === player && board[1][1] === player && board[2][0] === player); |
| 48 | + }; |
| 49 | + |
| 50 | + const xWin = hasWon('X'); |
| 51 | + const oWin = hasWon('O'); |
| 52 | + |
| 53 | + if (xWin && xCount !== oCount + 1) return false; |
| 54 | + if (oWin && xCount !== oCount) return false; |
| 55 | + if (xWin && oWin) return false; |
| 56 | + |
| 57 | + return true; |
| 58 | +}; |
0 commit comments