LeetCode //C - 1275. Find Winner on a Tic Tac Toe Game
1275. Find Winner on a Tic Tac Toe GameTic-tac-toe is played by two players A and B on a 3 x 3 grid. The rules of Tic-Tac-Toe are:Players take turns placing characters into empty squares ’ .The first player A always places ‘X’ characters, while the second player B always places ‘O’ characters.‘X’ and ‘O’ characters are always placed into empty squares, never on filled ones.The game ends when there are three of the same (non-empty) character filling any row, column, or diagonal.The game also ends if all squares are non-empty.No more moves can be played if the game is over.Given a 2D integer array moves wherem o v e s [ i ] [ r o w i , c o l i ] moves[i] [row_i, col_i]moves[i][rowi,coli]indicates that thei t h i^{th}ithmove will be played ong r i d [ r o w i ] [ c o l i ] grid[row_i][col_i]grid[rowi][coli]. return the winner of the game if it exists (A or B). In case the game ends in a draw return “Draw”. If there are still movements to play return “Pending”.You can assume that moves is valid (i.e., it follows the rules of Tic-Tac-Toe), the grid is initially empty, and A will play first.Example 1:Input:moves [[0,0],[2,0],[1,1],[2,1],[2,2]]Output:“A”Explanation:A wins, they always play first.Example 2:Input:moves [[0,0],[1,1],[0,1],[0,2],[1,0],[2,0]]Output:“B”Explanation:TB wins.Example 3:Input:moves [[0,0],[1,1],[2,0],[1,0],[1,2],[2,1],[0,1],[0,2],[2,2]]Output:“Draw”Explanation:The game ends in a draw since there are no moves to make.Constraints:1 moves.length 9moves[i].length 20 r o w i , c o l i 2 0 row_i, col_i 20rowi,coli2There are no repeated elements on moves.moves follow the rules of tic tac toe.From: LeetCodeLink: 1275. Find Winner on a Tic Tac Toe GameSolution:Ideas:put A as 1, B as -1.If any row, column, or diagonal sums to 3, A wins.If it sums to -3, B wins.Code:char*tictactoe(int**moves,intmovesSize,int*movesColSize){intboard[3][3]{0};// A 1, B -1for(inti0;imovesSize;i){intrmoves[i][0];intcmoves[i][1];board[r][c](i%20)?1:-1;}for(inti0;i3;i){introwboard[i][0]board[i][1]board[i][2];intcolboard[0][i]board[1][i]board[2][i];if(row3||col3)returnA;if(row-3||col-3)returnB;}intdiag1board[0][0]board[1][1]board[2][2];intdiag2board[0][2]board[1][1]board[2][0];if(diag13||diag23)returnA;if(diag1-3||diag2-3)returnB;if(movesSize9)returnDraw;returnPending;}
上一篇/下一篇内容由系统自动关联
返回资讯列表 →