Find Winner on a Tic Tac Toe Game

Problem Id: 1275 Difficulty: Easy Tag: Array


Intuition

This is a simple problem. First, we need to build up the grid after several moves. Then, we check if the game has finished and does anyone wins. Finally, check if it is a draw or pending.

Solution


class Solution:
    def tictactoe(self, moves: List[List[int]]) -> str:
        grid = [[None] * 3 for _ in range(3)]
        A = True
        for i, j in moves:
            grid[i][j] = A
            A = not A

        possiblities = []
        for i in range(3):
            ways = []
            for j in range(3):
                ways.append([i, j])
            possiblities.append(ways)
        for j in range(3):
            ways = []
            for i in range(3):
                ways.append([i, j])
            possiblities.append(ways)
        possiblities.append([[0, 0], [1, 1], [2, 2]])
        possiblities.append([[2, 0], [1, 1], [0, 2]])

        for ways in possiblities:
            A = True
            B = True
            pending = False
            for i, j in ways:
                if grid[i][j] is None:
                    pending = True
                    break
                elif grid[i][j] == True:
                    B = False
                else:
                    A = False
            if pending:
                continue
            elif A:
                return 'A'
            elif B:
                return 'B'

        for i in range(3):
            for j in range(3):
                if grid[i][j] is None:
                    return 'Pending'
        return 'Draw'