794. Valid Tic-Tac-Toe State
Problem Description
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.
Analysis
A direct thought is judging whether the current board is valid. Count all the ‘X’ and all the ‘O’, and it requires num('X') >= num('O')
and num('X') - num('O') <= 1
. Then we use dp to take a look at which position may be the last step. Then we should check if the game terminates before this step. Here is the code:
class Solution {
public:
bool validTicTacToe(vector<string>& board) {
int numX = 0, numO = 0;
for (int i=0; i<3; i++) {
for (int j=0; j<3; j++) {
if (board[i][j] == 'X') numX++;
if (board[i][j] == 'O') numO++;
}
}
if (numX - numO > 1 || numX - numO < 0) return false;
if (numO == 0) return true;
bool flag = false;
bool choose = numX > numO ? true : false;
for (int i=0; i<3; i++) {
for (int j=0; j<3; j++) {
if (board[i][j] == (choose ? 'X' : 'O')) {
vector<string> tmp(board);
tmp[i][j] = ' ';
if (isValid(tmp)) {
flag |= validTicTacToe(tmp);
}
}
}
}
return flag;
}
bool isValid(vector<string>& board) {
for (int i=0; i<3; i++) {
if (board[i][0] != ' ' && board[i][0] == board[i][1] && board[i][1] == board[i][2]) return false;
if (board[0][i] != ' ' && board[1][i] == board[0][i] && board[2][i] == board[1][i]) return false;
}
if (board[0][0] != ' ' && board[1][1] == board[2][2] && board[0][0] == board[1][1]) return false;
if (board[2][0] != ' ' && board[2][0] == board[1][1] && board[1][1] == board[0][2]) return false;
return true;
}
};