Who won the tic-tac-toe game
A completed 3x3 tic-tac-toe board is given. Determine which player won, or if it is a draw.
- The board is a 3x3 grid of integers: 0 means empty, 1 is player one, 2 is player two.
- A player wins by filling an entire row, column, or diagonal with their value.
- Return the winning player's number, or 0 if nobody won.
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.
Where you start
int ticTacToeWinner(List<List<Integer>> board) {
}
Worked examples
| Call | Result |
|---|---|
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;
}