
Sponsored
Sponsored
In this approach, we use a 3x3 board to simulate the mechanics of a Tic Tac Toe game. For every move made, we place the respective player's symbol ('X' for player A and 'O' for player B) on the board. After each move, we check if this move results in a win for any player by verifying if there are three matching symbols in any row, column, or diagonal. If a win is found, that player is declared the winner and the game ends. If all moves are exhausted without a winner, the game is declared a draw. If there are remaining moves, the game is pending.
Time Complexity: O(n), where n is the length of the moves. In the worst case, it checks 8 winning conditions for all 9 moves.
Space Complexity: O(1), since the board is of fixed size (3x3).
1class Solution {
2 public String tictactoe(int[][] moves) {
3 char[][] board = new char[3]
The solution initializes a 3x3 board and applies moves alternately by players A and B. After executing all moves, it verifies if either player has achieved a winning condition by checking each row, column, and diagonal. The status is updated with "A", "B", "Draw", or "Pending" accordingly.
Instead of simulating the grid itself, this approach tracks the status of each row, column, and the two diagonals using counters. Each player will have their counters, incrementing or decrementing upon making a move. The first instance a counter reaches 3 or -3 indicates a player has won the game. This method significantly reduces the need to check the grid extensively for each move while still adhering to the rules of Tic Tac Toe.
Time Complexity: O(n), where n is the number of moves.
Space Complexity: O(1), as only fixed-size counters are involved.
#include <vector>
#include <cmath>
using namespace std;
string tictactoe(vector<vector<int>>& moves) {
vector<int> row(3, 0), col(3, 0);
int diag = 0, anti_diag = 0;
int player = 1;
for (auto& move : moves) {
int r = move[0], c = move[1];
row[r] += player;
col[c] += player;
if (r == c) diag += player;
if (r + c == 2) anti_diag += player;
if (abs(row[r]) == 3 || abs(col[c]) == 3 || abs(diag) == 3 || abs(anti_diag) == 3)
return player == 1 ? "A" : "B";
player = -player;
}
return moves.size() == 9 ? "Draw" : "Pending";
}
int main() {
vector<vector<int>> moves = {{0,0},{2,0},{1,1},{2,1},{2,2}};
cout << tictactoe(moves) << endl;
return 0;
}
This approach leverages vectors to maintain scores for each row, column, and diagonal. The player alternation is expressed via the integer values -1 and 1. Once any score attains the absolute value of 3, a win is confirmed for the respective player.