Leetcode 348 Solution
This article provides solution to leetcode question 348 (design-tic-tac-toe)
Access this page by simply typing in "lcs 348" in your browser address bar if you have bunnylol configured.
Leetcode Question Link
https://leetcode.com/problems/design-tic-tac-toe
Solution
class TicTacToe {
vector<vector<int>> board;
int m_n;
public:
/** Initialize your data structure here. */
TicTacToe(int n) {
m_n = n;
board = vector<vector<int>>(n, vector<int>(n));
}
/** 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;
bool win = true;
for (int i = 0; i < m_n; i++)
if (board[i][col] != player)
{
win = false;
break;
}
if (win == true)
return player;
win = true;
for (int i = 0; i < m_n; i++)
if (board[row][i] != player)
{
win = false;
break;
}
if (win == true)
return player;
if (row == col || row + col == m_n - 1)
{
bool win1 = true;
bool win2 = true;
for (int i = 0; i < m_n; i++)
{
if (board[i][i] != player)
win1 = false;
if (board[i][m_n - i - 1] != player)
win2 = false;
if (win1 == false && win2 == false)
break;
}
if (win1 || win2)
return player;
}
return 0;
}
};
/**
* Your TicTacToe object will be instantiated and called as such:
* TicTacToe obj = new TicTacToe(n);
* int param_1 = obj.move(row,col,player);
*/