Is the Tic-Tac-Toe Game Over?
You are given the current state of an n x n Tic-Tac-Toe board. Each cell is "X", "O" or "" (empty). Implement gameOver(board), which returns true when the game has ended and false when it is still in progress.
The game has ended when either player has filled an entire row, an entire column, or one of the two main diagonals with their mark, or when the board is full with no winner.
[["X", "O", ""], ["O", "X", ""], -> true // X holds the main diagonal ["", "", "X"]] [["X", "O", ""], ["", "X", ""], -> false ["", "", "O"]]
The result is a boolean, not the winner. You are expected to write and run a test for each situation. The follow-up asks for a faster check when moves arrive one at a time.
Hints
Hint 1
A line is won when its first cell is not empty and every other cell in the line equals it.
Hint 2
There are 2n + 2 lines. Check them all, then check whether any cell is still empty.
Hint 3
For the follow-up, keep one counter per row, per column and per diagonal: add 1 for an X and subtract 1 for an O. A move wins when a counter it touches reaches n or -n.
Topics
Asked at
Sign in to use the assistant — ask what the problem means, get a hint when you're stuck, or have your current work reviewed. Conversations save to your account.