Drill

ProblemsC# › games

Who won the tic-tac-toe game

hardgamesGridsArraysC#

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

C# 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

public int TicTacToeWinner(List<List<int>> board) {
    
}

Worked examples

CallResult
TicTacToeWinner(new List<List<int>> { new List<int> { 1, 1, 1 }, new List<int> { 0, 2, 0 }, new List<int> { 2, 0, 2 } })1
TicTacToeWinner(new List<List<int>> { new List<int> { 2, 0, 1 }, new List<int> { 2, 0, 1 }, new List<int> { 2, 1, 0 } })2
TicTacToeWinner(new List<List<int>> { new List<int> { 1, 2, 1 }, new List<int> { 0, 1, 2 }, new List<int> { 2, 0, 1 } })1
TicTacToeWinner(new List<List<int>> { new List<int> { 0, 1, 2 }, new List<int> { 1, 2, 0 }, new List<int> { 2, 0, 0 } })2

Hint

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

Reference solution in C#
public int TicTacToeWinner(List<List<int>> board) {
    for (int i = 0; i < 3; i++) {
        if (board[i][0] != 0 && board[i][0] == board[i][1] && board[i][1] == board[i][2]) return board[i][0];
        if (board[0][i] != 0 && board[0][i] == board[1][i] && board[1][i] == board[2][i]) return board[0][i];
    }
    if (board[0][0] != 0 && board[0][0] == board[1][1] && board[1][1] == board[2][2]) return board[0][0];
    if (board[0][2] != 0 && board[0][2] == board[1][1] && board[1][1] == board[2][0]) return board[0][2];
    return 0;
}

The same problem in another language

More games problems in C#