In this great book, we're asked to design an algorithm to figure out if someone has won in a game of tic-tac-toe. The following solution is given, after which the author said:
Note that the runtime could be reduced to O(N) with the addition of row and column count arrays (and two sums for the diagonals)
I tried hard, but I couldn't figure out the meaning of that remark. How are these arrays and sums added ? Thanks !
enum Piece { Empty, Red, Blue };
enum Check { Row, Column, Diagonal, ReverseDiagonal }
Piece getIthColor(Piece[][] board, int index, int var, Check check) {
if (check == Check.Row) return board[index][var];
else if (check == Check.Column) return board[var][index];
else if (check == Check.Diagonal) return board[var][var];
else if (check == Check.ReverseDiagonal)
return board[board.length - 1 - var][var];
return Piece.Empty;
}
Piece getWinner(Piece[][] board, int fixed_index, Check check) {
Piece color = getIthColor(board, fixed_index, 0, check);
if (color == Piece.Empty) return Piece.Empty;
for (int var = 1; var < board.length; var++) {
if (color != getIthColor(board, fixed_index, var, check)) {
return Piece.Empty;
}
}
return color;
}
Piece hasWon(Piece[][] board) {
int N = board.length;
Piece winner = Piece.Empty;
// Check rows and columns
for (int i = 0; i < N; i++) {
winner = getWinner(board, i, Check.Row);
if (winner != Piece.Empty) {
return winner;
}
winner = getWinner(board, i, Check.Column);
if (winner != Piece.Empty) {
return winner;
}
}
winner = getWinner(board, -1, Check.Diagonal);
if (winner != Piece.Empty) {
return winner;
}
// Check diagonal
winner = getWinner(board, -1, Check.ReverseDiagonal);
if (winner != Piece.Empty) {
return winner;
}
return Piece.Empty;
}
Each time a new piece is placed in the board, you increase the appropriate row, column and (possibly ) diagonal counters by 1. You either have separate counters for the players, or use +1/-1.
Now when you check the board, you only have to check whether any of this counters equals N, which can be done in O(N) (2N+2 counters).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With