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 TicTacToeTicTacToe(n)move(row, col, player)
Example
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
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.
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 rowcolrow == colrow + col == n - 1
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
Java Solution
The class TicTacToe
- The field
holds the size of the board, which is also the total a full line reaches.n - The arrays
androws hold one total for each row and for each column, +1 for every X and -1 for every O.cols - The fields
anddiagonal hold the totals of the two corner-to-corner lines.antiDiagonal - The method
turns the player intomove , +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.add - The helpers
andtotals serveplay . The first returns the totals as text, and the second plays a list of moves on a board and prints what eachmain call returns, on one line.move
The main
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:
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=1antiDiagonal=-1
In 0 0 0 0 2
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
androws hold n numbers each and each diagonal needs one, where a stored board would need n² squares.cols
Counting instead of looking at the cells again also comes up in