题目大意:判断一个井字棋的棋盘是否有效。
A Tic-Tac-Toe board is given as a string array board
. Return True if and only if it is possible to reach this board position during the course of a valid tic-tac-toe game.
The board
is a 3 x 3 array, and consists of characters " "
, "X"
, and "O"
. The ” ” character represents an empty square.
Here are the rules of Tic-Tac-Toe:
- Players take turns placing characters into empty squares (” “).
- The first player always places “X” characters, while the second player always places “O” characters.
- “X” and “O” characters are always placed into empty squares, never filled ones.
- The game ends when there are 3 of the same (non-empty) character filling any row, column, or diagonal.
- The game also ends if all squares are non-empty.
- No more moves can be played if the game is over.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
Example 1: Input: board = ["O ", " ", " "] Output: false Explanation: The first player always plays "X". Example 2: Input: board = ["XOX", " X ", " "] Output: false Explanation: Players take turns making moves. Example 3: Input: board = ["XXX", " ", "OOO"] Output: false Example 4: Input: board = ["XOX", "O O", "XOX"] Output: true |
Note:
board
is a length-3 array of strings, where each stringboard[i]
has length 3.- Each
board[i][j]
is a character in the set{" ", "X", "O"}
.
Idea: Verify all rules
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
class Solution { public: bool validTicTacToe(vector<string>& board) { int x = 0; int o = 0; int wins_x = getWins(board, 'X', x); int wins_o = getWins(board, 'O', o); return wins_x + wins_o <= 1 && x >= o + wins_x && x <= o + 1 - wins_o; } private: int getWins(const vector<string>& board, char p, int& count) { vector<string> rows(3); string diag1, diag2; for (int i = 0; i < 3; ++i) { diag1 += board[i][i]; diag2 += board[i][2 - i]; for (int j = 0; j < 3; ++j) { char c = board[i][j]; rows[j] += c; count += c == p; } } string win(3, p); int wins = (diag1 == win) + (diag2 == win); for (int i = 0; i < 3; ++i) { wins += rows[i] == win; wins += board[i] == win; } return wins; } }; |