You are given an array moves
where each element represents a move made by players in a game of Tic Tac Toe on a 3x3 board. The moves array contains elements in the form [row, col]
:
The output should be “A” if Player A wins, “B” if Player B wins, “Draw” if no one wins and all cells are filled, and “Pending” if the game is still ongoing.
def tictactoe(moves):
# Initialize the board as a 3x3 grid
board = [["" for _ in range(3)] for _ in range(3)]
# Fill the board based on the moves
for i, (r, c) in enumerate(moves):
if i % 2 == 0: # Player A's move
board[r][c] = 'A'
else: # Player B's move
board[r][c] = 'B'
# Function to check for a winning condition
def check_winner(player):
# Check rows, columns, and both diagonals
for row in board:
if all(cell == player for cell in row):
return True
for col in range(3):
if all(board[row][col] == player for row in range(3)):
return True
if all(board[i][i] == player for i in range(3)):
return True
if all(board[i][2 - i] == player for i in range(3)):
return True
return False
# Check if A or B has won
if check_winner('A'):
return "A"
if check_winner('B'):
return "B"
# If no one has won, check if the board is full
if len(moves) == 9:
return "Draw"
# If there are remaining moves, return pending
return "Pending"
check_winner
to determine if a player has three marks in any row, column, or diagonal.Thus, the overall time complexity is ( O(N) ), where ( N ) is the number of moves.
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?