Mark alternating moves on a three-by-three board, test all rows, columns, and diagonals, then distinguish draw from pending by move count.
Complexity
O(m) time for the moves and O(1) space.
Determine the winner or current state after a valid sequence of tic-tac-toe moves.
Mark alternating moves on a three-by-three board, test all rows, columns, and diagonals, then distinguish draw from pending by move count.
O(m) time for the moves and O(1) space.
package main
func tictactoe(moves [][]int) string {
board := [3][3]int{}
for index, move := range moves {
if index%2 == 0 {
board[move[0]][move[1]] = 1
} else {
board[move[0]][move[1]] = -1
}
}
for index := 0; index < 3; index++ {
row, column := 0, 0
for offset := 0; offset < 3; offset++ {
row += board[index][offset]
column += board[offset][index]
}
if row == 3 || column == 3 {
return "A"
}
if row == -3 || column == -3 {
return "B"
}
}
first, second := board[0][0]+board[1][1]+board[2][2], board[0][2]+board[1][1]+board[2][0]
if first == 3 || second == 3 {
return "A"
}
if first == -3 || second == -3 {
return "B"
}
if len(moves) == 9 {
return "Draw"
}
return "Pending"
}
class Solution:
def tictactoe(self, moves: list[list[int]]) -> str:
board = [[0] * 3 for _ in range(3)]
for index, (row, column) in enumerate(moves): board[row][column] = 1 if index % 2 == 0 else -1
lines = board + [list(column) for column in zip(*board)] + [[board[i][i] for i in range(3)], [board[i][2 - i] for i in range(3)]]
for line in lines:
if sum(line) == 3: return "A"
if sum(line) == -3: return "B"
return "Draw" if len(moves) == 9 else "Pending"
function tictactoe(moves: number[][]): string {
const board = Array.from({ length: 3 }, () => new Array<number>(3).fill(0)); moves.forEach(([row, column], index) => { board[row][column] = index % 2 === 0 ? 1 : -1; });
const lines = [...board, ...[0, 1, 2].map((column) => board.map((row) => row[column])), [board[0][0], board[1][1], board[2][2]], [board[0][2], board[1][1], board[2][0]]];
for (const line of lines) { const sum = line.reduce((total, value) => total + value, 0); if (sum === 3) return "A"; if (sum === -3) return "B"; }
return moves.length === 9 ? "Draw" : "Pending";
}