1. Title
Design an algorithm to determine whether the player has won the tic-tac-toe game. The input is an N x N array checkerboard, consisting of the characters "", "X" and "O", where the character "" represents an empty slot.
Here are the rules of the tic-tac-toe game:
- Players take turns putting characters into empty slots ("").
- The first player always puts the character "O", and the second player always puts the character "X".
- "X" and "O" are only allowed to be placed in vacancies, and not allowed to fill the positions where characters have been placed.
- When there are N identical (and non-empty) characters filling any row, column, or diagonal, the game ends and the player corresponding to the character wins.
- When all positions are not empty, it is also regarded as the end of the game.
- If the game is over, the player is not allowed to place any more characters.
If there is a winner in the game, the character used by the winner of the game ("X" or "O")
is returned ; if the game ends in a draw, then "Draw" is returned;
if there is still action (the game is not over), then Return to "Pending".
示例 1:
输入: board = ["O X"," XO","X O"]
输出: "X"
示例 2:
输入: board = ["OOX","XXO","OXO"]
输出: "Draw"
解释: 没有玩家获胜且不存在空位
示例 3:
输入: board = ["OOX","XXO","OX "]
输出: "Pending"
解释: 没有玩家获胜且仍存在空位
提示:
1 <= board.length == board[i].length <= 100
输入一定遵循井字棋规则
Source: LeetCode
Link: https://leetcode-cn.com/problems/tic-tac-toe-lcci
Copyright belongs to Deduction Network. Please contact the official authorization for commercial reprint, and please indicate the source for non-commercial reprint.
2. Problem solving
- Similar topics: LeetCode 1275. Find the winner of Tic Tac Toe (bit operation)
- Count by row, column, diagonal
class Solution {
public:
string tictactoe(vector<string>& board) {
int n = board.size(), i, j, count = 0;
vector<int> ra(n,0);//玩家1 的行
vector<int> ca(n,0);//玩家1 的列
vector<int> rb(n,0);
vector<int> cb(n,0);
int xa1 = 0, xa2 = 0, xb1 = 0, xb2 = 0;//对角线2条
for(i = 0; i < n; ++i)
{
for(j = 0; j < n; ++j)
{
if(board[i][j]=='X')
{
ra[i]++;
ca[j]++;
if(i==j) xa1++;
if(i+j==n-1) xa2++;
count++;
}
else if(board[i][j]=='O')
{
rb[i]++;
cb[j]++;
if(i==j) xb1++;
if(i+j==n-1) xb2++;
count++;
}
}
}
char win = '-';
for(i = 0; i < n; ++i)
{
if(ra[i]==n || ca[i]==n ||xa1==n || xa2==n)
{
win = 'X';
break;
}
if(rb[i]==n || cb[i]==n || xb1==n || xb2==n)
{
win = 'O';
break;
}
}
if(win=='X') return "X";
if(win=='O') return "O";
if(count == n*n) return "Draw";
return "Pending";
}
};
8 ms 8.3 MB