Design a Tic-tac-toe game that is played between two players on a n x n grid.
You may assume the following rules:
A move is guaranteed to be valid and is placed on an empty block. Once a winning condition is reached, no more moves is allowed. A player who succeeds in placing n of their marks in a horizontal, vertical, or diagonal row wins the game.
// 28ms, 95%
class TicTacToe {
vector<int> rows;
vector<int> cols;
int d1;
int d2;
public:
/** Initialize your data structure here. */
TicTacToe(int n) {
rows.resize(n, 0);
cols.resize(n, 0);
d1 = d2 = 0;
}
/** Player {player} makes a move at ({row}, {col}).
@param row The row of the board.
@param col The column of the board.
@param player The player, can be either 1 or 2.
@return The current winning condition, can be either:
0: No one wins.
1: Player 1 wins.
2: Player 2 wins. */
int move(int row, int col, int player) {
const int N = rows.size();
const int score = player == 1? 1:-1;
rows[row] += score;
cols[col] += score;
if (row == col) d1 += score;
if (row + col == N-1)
d2 += score;
const int WIN = score*N;
return (rows[row] == WIN ||
cols[col] == WIN ||
d1 == WIN ||
d2 == WIN)? player: 0;
}
};
// 40ms, 40%
class TicTacToe {
vector<vector<int>> board;
public:
/** Initialize your data structure here. */
TicTacToe(int n) {
board.resize(n, vector<int>(n, 0));
}
/** Player {player} makes a move at ({row}, {col}).
@param row The row of the board.
@param col The column of the board.
@param player The player, can be either 1 or 2.
@return The current winning condition, can be either:
0: No one wins.
1: Player 1 wins.
2: Player 2 wins. */
int move(int row, int col, int player) {
board[row][col] = player;
int rcnt = 0, ccnt = 0, dcnt1 = 0, dcnt2 = 0;
const int N = board.size();
auto checkd1 = row == col;
auto checkd2 = row + col == N - 1;
for (int i = 0; i < N; i++) {
rcnt += board[row][i] == player;
ccnt += board[i][col] == player;
if (checkd1) {
dcnt1 += board[i][i] == player;
}
if (checkd2) {
dcnt2 += board[N-i-1][i] == player;
}
}
return rcnt == N || ccnt == N || dcnt1 == N || dcnt2 == N? player: 0;
}
};
/**
* Your TicTacToe object will be instantiated and called as such:
* TicTacToe* obj = new TicTacToe(n);
* int param_1 = obj->move(row,col,player);
*/