Problem overview
You build a TicTacToe class for two players, X and O, on a 3 by 3 board. One object is one game: it remembers the board and whose turn it is. Rows and columns are numbered 0 to 2, with cell (0, 0) at the top left. A cell holds 'X', 'O', or '.' when it is empty.
- The constructor
TicTacToe()fills the privatechar board[3][3]with dots and setsplayer = 'X', so X moves first. void move(int r, int c)plays a turn. If the cell is taken, the call changes nothing and it is still the same player's turn. Otherwise the current player's mark goes in the cell and the turn passes to the other player. The coordinates are always 0 to 2, so no range check is needed.char winner()returns'X'or'O'when that player has three in a row, in a column or on one of the two diagonals, and'.'otherwise. That covers a game in progress, an empty board and a draw.
The code at the bottom of the starter plays six games. In the first, X takes the whole top row. In the second, X tries to play on cell (0, 0) a second time. The call is ignored and it is still X's turn, so X plays (1, 0), and O goes on to complete the middle column. The third and fourth games finish on the two diagonals for X. The fifth fills the board with no line, and the sixth is a fresh game. The output:
X wins!
O wins!
X wins!
X wins!
No winner: .
No winner: .
Approach: eight lines, one test
A game is won by one of eight lines: three rows, three columns and two diagonals. Every line has the same test: its three cells are equal and not empty. The second part of the test matters because three dots are equal to each other too, but they are not a win.
A loop with i from 0 to 2 can check row i and column i together: the row's cells are board[i][0], board[i][1] and board[i][2], and the column's are the same indexes swapped. The two diagonals don't depend on i, so they are checked once after the loop. The method returns the mark of the first complete line it finds, and a dot if none is complete.
For move, the order of the operations matters. First check whether the cell is taken and leave if it is, before touching the board or the turn. Only a successful move passes the turn on. This is what keeps the player the same after a rejected move.
Step by step
- Declare
TicTacToewithprivate:andpublic:labels and the closing};. - Add the board under
private:aschar board[3][3];.board[r][c]is the cell in rowr, columnc. - Add
char player;for whose turn it is. - Write the constructor under
public:: the class name, no return type. - Loop over the rows with
i. - Nest a loop over the columns with
j. - Set
board[i][j]to'.'. The nested loops visit all nine cells. - Set
playerto'X'below the loops, so every new game starts with X. - Start
moveas avoidmethod with parametersrandc. - Guard a taken cell. If
board[r][c]isn't'.', return at once: nothing changes and the turn stays. - Place the mark:
board[r][c] = player;. - Pass the turn with a conditional expression: if the player was
'X'it becomes'O', otherwise'X'. - Start
winneras a method returningchar. - Loop
iover 0, 1 and 2, each pass checking rowiand columni. - Check row
i: the first cell isn't a dot and equals the second, and the second equals the third. Then return that mark. - Check column
ithe same way, with the two indexes swapped. - Check the main diagonal, cells (0,0), (1,1) and (2,2), after the loop.
- Check the other diagonal, cells (0,2), (1,1) and (2,0): the row goes up by one as the column goes down by one.
- Return
'.'as the last line: every check failed, so nobody has won.
The solution in C++
class TicTacToe {
private:
char board[3][3];
char player;
public:
TicTacToe() {
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
board[i][j] = '.';
player = 'X';
}
void move(int r, int c) {
if (board[r][c] != '.') return;
board[r][c] = player;
player = (player == 'X') ? 'O' : 'X';
}
char winner() {
for (int i = 0; i < 3; i++) {
if (board[i][0] != '.' && board[i][0] == board[i][1] && board[i][1] == board[i][2]) return board[i][0];
if (board[0][i] != '.' && board[0][i] == board[1][i] && board[1][i] == board[2][i]) return board[0][i];
}
if (board[0][0] != '.' && board[0][0] == board[1][1] && board[1][1] == board[2][2]) return board[0][0];
if (board[0][2] != '.' && board[0][2] == board[1][1] && board[1][1] == board[2][0]) return board[0][2];
return '.';
}
};
class Solution {
public:
void mainFunction() {
TicTacToe game;
game.move(0, 0);
game.move(1, 0);
game.move(0, 1);
game.move(1, 1);
game.move(0, 2);
cout << game.winner() << " wins!" << endl;
game = TicTacToe();
game.move(0, 0);
game.move(0, 1);
game.move(0, 0);
game.move(1, 0);
game.move(1, 1);
game.move(2, 2);
game.move(2, 1);
cout << game.winner() << " wins!" << endl;
game = TicTacToe();
game.move(0, 0);
game.move(0, 1);
game.move(1, 1);
game.move(0, 2);
game.move(2, 2);
cout << game.winner() << " wins!" << endl;
game = TicTacToe();
game.move(0, 2);
game.move(0, 0);
game.move(1, 1);
game.move(0, 1);
game.move(2, 0);
cout << game.winner() << " wins!" << endl;
game = TicTacToe();
game.move(0, 0);
game.move(0, 1);
game.move(0, 2);
game.move(1, 1);
game.move(1, 0);
game.move(1, 2);
game.move(2, 1);
game.move(2, 0);
game.move(2, 2);
cout << "No winner: " << game.winner() << endl;
game = TicTacToe();
cout << "No winner: " << game.winner() << endl;
}
};
C++ details worth knowing
- The constructor must fill the board. A
chararray that is a class member isn't set to anything automatically. Without the loops, the cells would hold unpredictable values, and the test for an empty cell would fail. - Characters use single quotes.
'X'is onechar;"X"is a string and can't be assigned to achar. - Printing a
char.cout << game.winner()prints the character itself, which is why the output readsX wins!. - The conditional expression.
test ? a : bgivesawhen the test is true andbotherwise, which makes the turn change a single line. - Resetting a game.
game = TicTacToe();builds a new object, so the constructor runs again, and copies it over the old one. Every cell is a dot again and X is back on move. - The row-then-column check. Each check uses
&&, which stops at the first false part, so the equality tests only run for a non-empty first cell.
Complexity
The board has a fixed size, so everything takes constant time. The constructor visits nine cells, move writes one, and winner checks eight lines of three cells each. The class stores nine characters and one more for the player.
Edge cases and common mistakes
- Letting a taken cell be overwritten. Without the guard, the second
move(0, 0)in the second game would replace X's mark and hand the turn to O. The board would differ from the expected game. - Passing the turn on a rejected move. Putting the turn change before the guard would give O the turn after X's refused move, which breaks the sequence.
- Skipping the "not a dot" test. Three empty cells are equal to each other, so an empty row would be reported as a win for
'.'. The method would return at that line and never reach a real winning line further down the board. Always check that the first cell holds a mark. - Mixing up the diagonals. The second diagonal is (0,2), (1,1), (2,0), not (0,2), (1,1), (2,2).
- A missing final
return. Acharmethod that can reach its end without returning is undefined behaviour. The linereturn '.';covers games in progress and draws.
Testing
For the second game, after the moves (0,0), (0,1), (0,0), (1,0), (1,1), (2,2) and (2,1), the repeated (0,0) was ignored, so X is still to move. The board looks like this, and column 1 holds three O marks:
XO.
XO.
.OX
turn: X
Other cases to try are a new game (the winner is '.') and a game with two marks each (still '.'). The drawn board in the fifth game also returns '.'.
Key takeaways
- One object is one game: the board and the current player are its private state.
- Guard first in
move, then place the mark, then pass the turn. - A win is one of eight lines; test that the first cell isn't empty and that the three cells match.
