- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 51 lines of C++ from the credited upstream file 348.cpp.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class TicTacToe {2 public:3 TicTacToe(int n) : n(n), rows(n), cols(n) {}4 5 /**6 * Player {player} makes a move at ({row}, {col}).7 *8 * @param row The row of the board.9 * @param col The column of the board.10 * @param player The player, can be either 1 or 2.11 * @return The current winning condition, can be either:12 * 0: No one wins.13 * 1: Player 1 wins.14 * 2: Player 2 wins.15 */16 int std::move(int row, int col, int player) {17 const int toAdd = player == 1 ? 1 : -1;18 const int target = player == 1 ? n : -n;19 20 if (row == col) {21 diag += toAdd;22 if (diag == target)23 return player;24 }25 26 if (row + col == n - 1) {27 antiDiag += toAdd;28 if (antiDiag == target)29 return player;30 }31 32 rows[row] += toAdd;33 if (rows[row] == target)34 return player;35 36 cols[col] += toAdd;37 if (cols[col] == target)38 return player;39 40 return 0;41 }42 43 private:44 const int n;45 46 vector<int> rows;47 vector<int> cols;48 int diag = 0;49 int antiDiag = 0;50};51