Implement a function to check if a given Tic-Tac-Toe board state is valid. The board is a 3x3 array where each element is either 'X'
, 'O'
, or ' '
. A valid Tic-Tac-Toe board must satisfy the following conditions:
Write a function bool validTicTacToe(vector<string>& board)
to return whether the given board state is valid.
#include <vector>
#include <string>
using namespace std;
bool isWinner(const vector<string>& board, char player) {
// Check rows and columns
for (int i = 0; i < 3; ++i) {
if (board[i][0] == player && board[i][1] == player && board[i][2] == player) return true;
if (board[0][i] == player && board[1][i] == player && board[2][i] == player) return true;
}
// Check diagonals
if (board[0][0] == player && board[1][1] == player && board[2][2] == player) return true;
if (board[0][2] == player && board[1][1] == player && board[2][0] == player) return true;
return false;
}
bool validTicTacToe(vector<string>& board) {
int countX = 0, countO = 0;
// Count X's and O's
for (const auto& row : board) {
for (const auto& cell : row) {
if (cell == 'X') ++countX;
if (cell == 'O') ++countO;
}
}
// If the number of 'O's is greater than 'X's, or 'X' is greater by more than 1, return false
if (countO > countX || countX > countO + 1) return false;
bool xWins = isWinner(board, 'X');
bool oWins = isWinner(board, 'O');
// If 'X' wins, then there should be exactly one more 'X' than 'O'
if (xWins && countX != countO + 1) return false;
// If 'O' wins, then the number of 'X' and 'O' should be equal
if (oWins && countX != countO) return false;
// If both 'X' and 'O' win, it's invalid
if (xWins && oWins) return false;
return true;
}
Thus, the overall time complexity is (O(1)).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?