Drill

ProblemsPython › games

Who won the tic-tac-toe game

hardgamesPython

A completed 3x3 tic-tac-toe board is given. Determine which player won, or if it is a draw.

tic_tac_toe_winner(board: list<list<int>>) → int

Solve it in the editor →

Where you start

def tic_tac_toe_winner(board: list[list[int]]) -> int:
    

Worked examples

CallResult
tic_tac_toe_winner([[1, 1, 1], [0, 2, 0], [2, 0, 2]])1
tic_tac_toe_winner([[2, 0, 1], [2, 0, 1], [2, 1, 0]])2
tic_tac_toe_winner([[1, 2, 1], [0, 1, 2], [2, 0, 1]])1
tic_tac_toe_winner([[0, 1, 2], [1, 2, 0], [2, 0, 0]])2

Hint

Check all three rows, all three columns, and both diagonals.

Reference solution in Python
def tic_tac_toe_winner(board: list[list[int]]) -> int:
    for i in range(3):
        if board[i][0] != 0 and board[i][0] == board[i][1] == board[i][2]:
            return board[i][0]
        if board[0][i] != 0 and board[0][i] == board[1][i] == board[2][i]:
            return board[0][i]
    if board[0][0] != 0 and board[0][0] == board[1][1] == board[2][2]:
        return board[0][0]
    if board[0][2] != 0 and board[0][2] == board[1][1] == board[2][0]:
        return board[0][2]
    return 0

The same problem in another language

More games problems in Python