Design Tic-Tac-Toe

Referee a game of tic-tac-toe on an n by n board by keeping one running total for each row, column and diagonal.

Write a class TicTacToe that referees a game of tic-tac-toe between player 1 and player 2 on an n × n board. The constructor TicTacToe(n) starts with an empty board. The method move(row, col, player) puts the player's mark on the square at that row and column, both counted from 0, and the square is always empty. It returns the player's number if this move fills a whole row, column or diagonal with that player's marks, and 0 otherwise.

Example
TicTacToe(3) starts an empty 3 × 3 board
move(0, 0, 1) returns 0
move(0, 2, 2) returns 0
move(2, 2, 1) returns 0
move(1, 1, 2) returns 0
move(2, 0, 1) returns 0
move(1, 0, 2) returns 0
move(2, 1, 1) returns 1, because player 1 now holds all of row 2
Solution

The Idea

Tic-tac-toe is usually played with pencil and paper on a grid of 3 × 3 squares. Two players take turns writing their mark in an empty square, X for player 1 and O for player 2. A player who fills a whole row, a whole column or a corner-to-corner diagonal with their own mark wins. Here the board can be any size n × n, and the class is the referee: after each move, it says whether that move won the game.

The picture shows the board from the example after all seven moves. Each square is named by its row and column, so "row 2, col 1" is the middle square of the bottom row. The X's sit at row 0, col 0, at row 2, col 0 and at row 2, col 2, and the O's at row 0, col 2, row 1, col 0 and row 1, col 1. The last move, outlined in orange, puts an X at row 2, col 1, and the bottom row now holds three X's.

The 3 by 3 board after the seven moves of the example, with X for player 1 and O for player 2. The row totals are 0, -2 and 3, the column totals 1, 0 and 0, the diagonal total 1 and the anti-diagonal total -1. Row 2 reaches 3, which equals n, so player 1 wins.

How does a referee notice that win? The obvious way is to look at the board again: go along row 2 and see that every square holds an X. But a line only needs one fact to be checked, whether all n of its squares belong to the same player. Can a single number per line carry that fact?

It can, if each X adds 1 to its line's total and each O subtracts 1. Look at the boxes labelled "row totals" on the right. Row 2 holds three X's, so its total is 1 + 1 + 1 = 3. Row 1 holds two O's and an empty square, which gives -2. Row 0 holds one X and one O, and they cancel to 0. Below the board, the first of the "column totals" is 1, from X, O and X in col 0.

The two dashed lines are the diagonals. The one labelled "diagonal" runs from row 0, col 0 down to row 2, col 2 and holds X, O and X, so its total is 1. The "anti-diagonal" runs from row 0, col 2 down to row 2, col 0 and holds O, O and X, which gives -1.

A line has n squares, and each adds at most 1, so its total reaches n only when every square holds an X. In the same way it falls to -n only when every square holds an O. So the referee never has to look at the board: it keeps one total per line, and a move wins when it brings one of its lines to n or -n.

Solution Approach

A referee can keep the whole board, which is simple but reads many squares on every move. Keeping totals instead leaves three things to settle: which totals to keep, which of them a move changes, and how a total shows a win.

Keeping the whole board

What would the most direct referee do? It stores an n × n array of marks and writes each move into it. Then it walks along the move's row and column, and along a diagonal if the square is on one, looking for a square that is empty or holds the other mark. That reads up to 4n squares per move, and the array needs n² squares. The totals replace all of it with a few additions per move.

Which totals to keep

How many lines can be filled? There are n rows, n columns and two corner-to-corner diagonals, so the class keeps an array of n row totals, an array of n column totals and two single numbers for the diagonals. A shorter slanted line has fewer than n squares and can never make a win.

Why the signs, and not a plain count of marks? A count says how full a line is, not whose marks fill it. A row that reads X, O, X has three marks and no winner. In a test version where both players add 1, that row reaches 3 and the method reports player 1 as the winner. Two separate counts per line, one for each player, would also work, but they need twice the numbers.

Which lines a move touches

Which totals does a move at row row, col col change? Its row total and its column total, always. It is on the diagonal when row == col, as at row 2, col 2. It is on the anti-diagonal when row + col == n - 1, as at row 2, col 0, where 2 + 0 = 2, which is n - 1 on the 3 × 3 board. The centre square of the 3 × 3 board, row 1, col 1, passes both tests and changes both diagonal totals.

Spotting a win

When does a move win? Only the totals it just changed can have reached n or -n, because every other line looks as it did after the previous move. So after the update, the method checks those totals. Taking the absolute value with Math.abs turns both n and -n into n, so one comparison covers both players. If any touched total matches, the method returns the player's number, otherwise 0.

Java Solution

The class TicTacToe keeps only the line totals, in these fields and methods:

  • The field n holds the size of the board, which is also the total a full line reaches.
  • The arrays rows and cols hold one total for each row and for each column, +1 for every X and -1 for every O.
  • The fields diagonal and antiDiagonal hold the totals of the two corner-to-corner lines.
  • The method move turns the player into add, +1 or -1, adds it to every line the square is on, and returns the player when one of those totals reaches n or -n.
  • The helpers totals and play serve main. The first returns the totals as text, and the second plays a list of moves on a board and prints what each move call returns, on one line.

The main method plays the example and prints its totals, then plays a game that player 2 wins on the anti-diagonal, a full board with no winner, and one move on a 1 × 1 board.

Java
import java.util.Arrays;

public class TicTacToe {

    private final int n;
    private final int[] rows;   // one total per row: +1 for player 1, -1 for player 2
    private final int[] cols;   // one total per column
    private int diagonal;       // the cells where row == col
    private int antiDiagonal;   // the cells where row + col == n - 1

    public TicTacToe(int n) {
        this.n = n;
        rows = new int[n];
        cols = new int[n];
    }

    // Returns the winner after this move (1 or 2), or 0 if there is none yet.
    public int move(int row, int col, int player) {
        int add = player == 1 ? 1 : -1;
        rows[row] += add;
        cols[col] += add;
        if (row == col) {
            diagonal += add;
        }
        if (row + col == n - 1) {
            antiDiagonal += add;
        }
        boolean won = Math.abs(rows[row]) == n || Math.abs(cols[col]) == n
                || (row == col && Math.abs(diagonal) == n)
                || (row + col == n - 1 && Math.abs(antiDiagonal) == n);
        return won ? player : 0;
    }

    String totals() {
        return "rows=" + Arrays.toString(rows) + " cols=" + Arrays.toString(cols)
                + " diagonal=" + diagonal + " antiDiagonal=" + antiDiagonal;
    }

    static void play(TicTacToe game, int[][] moves) {
        StringBuilder sb = new StringBuilder();
        for (int[] m : moves) {
            int winner = game.move(m[0], m[1], m[2]);
            sb.append(winner).append(' ');
        }
        System.out.println(sb.toString().trim());
    }

    public static void main(String[] args) {
        TicTacToe game = new TicTacToe(3);
        int[][] example = {{0, 0, 1}, {0, 2, 2}, {2, 2, 1}, {1, 1, 2},
                           {2, 0, 1}, {1, 0, 2}, {2, 1, 1}};
        play(game, example);
        System.out.println(game.totals());

        // player 2 fills the anti-diagonal
        play(new TicTacToe(3), new int[][] {{0, 2, 2}, {0, 0, 1}, {1, 1, 2},
                                            {0, 1, 1}, {2, 0, 2}});

        // a full board with no winner: every row, column and diagonal is mixed
        play(new TicTacToe(3), new int[][] {{0, 0, 1}, {0, 1, 2}, {0, 2, 1},
                                            {1, 1, 2}, {1, 0, 1}, {1, 2, 2},
                                            {2, 1, 1}, {2, 0, 2}, {2, 2, 1}});

        // a 1 x 1 board: the first move fills every line
        play(new TicTacToe(1), new int[][] {{0, 0, 2}});
    }
}

Running it prints:

Output
0 0 0 0 0 0 1
rows=[0, -2, 3] cols=[1, 0, 0] diagonal=1 antiDiagonal=-1
0 0 0 0 2
0 0 0 0 0 0 0 0 0
2

The example's seven moves return six 0s and then a 1: the move at row 2, col 1 completes row 2 for player 1. Under it, rows=[0, -2, 3], cols=[1, 0, 0], diagonal=1 and antiDiagonal=-1 are the same totals as in the picture.

In 0 0 0 0 2, player 2 puts an O at row 0, col 2, then row 1, col 1, then row 2, col 0. Those three squares make up the anti-diagonal, so its total falls to -3 and the fifth move returns 2. The nine 0s come from a full board whose rows read X, O, X, then X, O, O, then O, X, X. Every row, column and diagonal there holds both marks, so no total reaches 3 or -3.

The single 2 on the last line is the 1 × 1 board. Its one square is a row, a column and both diagonals at once, and a total of -1 already equals -n, so player 2 wins with the first move.

Complexity

Each move changes a fixed number of totals, and the board itself is never stored.

  • Time: O(1) per move, because a move updates at most four totals (its row, its column and up to two diagonals) and compares each with n, however large the board is. The constructor takes O(n) to create the two arrays.
  • Space: O(n), because rows and cols hold n numbers each and each diagonal needs one, where a stored board would need n² squares.

Counting instead of looking at the cells again also comes up in Game of Life, where each cell's next state depends on how many of its neighbours are alive.