Drill

ProblemsJava › games

Who won the tic-tac-toe game

hardgamesGridsArraysJava

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

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

Java needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

int ticTacToeWinner(List<List<Integer>> board) {
    
}

Worked examples

CallResult
ticTacToeWinner(Main.<List<Integer>>ls(Main.<Integer>ls(1, 1, 1), Main.<Integer>ls(0, 2, 0), Main.<Integer>ls(2, 0, 2)))1
ticTacToeWinner(Main.<List<Integer>>ls(Main.<Integer>ls(2, 0, 1), Main.<Integer>ls(2, 0, 1), Main.<Integer>ls(2, 1, 0)))2
ticTacToeWinner(Main.<List<Integer>>ls(Main.<Integer>ls(1, 2, 1), Main.<Integer>ls(0, 1, 2), Main.<Integer>ls(2, 0, 1)))1
ticTacToeWinner(Main.<List<Integer>>ls(Main.<Integer>ls(0, 1, 2), Main.<Integer>ls(1, 2, 0), Main.<Integer>ls(2, 0, 0)))2

Hint

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

Reference solution in Java
int ticTacToeWinner(List<List<Integer>> board) {
    for (int i = 0; i < 3; i++) {
        if (board.get(i).get(0) != 0 && board.get(i).get(0) == board.get(i).get(1) && board.get(i).get(1) == board.get(i).get(2)) return board.get(i).get(0);
        if (board.get(0).get(i) != 0 && board.get(0).get(i) == board.get(1).get(i) && board.get(1).get(i) == board.get(2).get(i)) return board.get(0).get(i);
    }
    if (board.get(0).get(0) != 0 && board.get(0).get(0) == board.get(1).get(1) && board.get(1).get(1) == board.get(2).get(2)) return board.get(0).get(0);
    if (board.get(0).get(2) != 0 && board.get(0).get(2) == board.get(1).get(1) && board.get(1).get(1) == board.get(2).get(0)) return board.get(0).get(2);
    return 0;
}

The same problem in another language

More games problems in Java