74th LeetCode Weekly Contest Valid Tic-Tac-Toe State
A Tic-Tac-Toe board is given as a string array board
. Return True if and only if it is possible to reach this board position during the course of a valid tic-tac-toe game.
The board
is a 3 x 3 array, and consists of characters " "
, "X"
, and "O"
. The " " character represents an empty square.
Here are the rules of Tic-Tac-Toe:
- Players take turns placing characters into empty squares (" ").
- The first player always places "X" characters, while the second player always places "O" characters.
- "X" and "O" characters are always placed into empty squares, never filled ones.
- The game ends when there are 3 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.
Example 1: Input: board = ["O ", " ", " "] Output: false Explanation: The first player always plays "X". Example 2: Input: board = ["XOX", " X ", " "] Output: false Explanation: Players take turns making moves. Example 3: Input: board = ["XXX", " ", "OOO"] Output: false Example 4: Input: board = ["XOX", "O O", "XOX"] Output: true
Note:
board
is a length-3 array of strings, where each stringboard[i]
has length 3.- Each
board[i][j]
is a character in the set{" ", "X", "O"}
.
判断井字棋是不是合法状态,想怎么判断就怎么判断吧
1 class Solution { 2 public: 3 char Board[3][3]; 4 bool check(int x,int y,int dx,int dy,char c){ 5 for(int i=0;i<3;i++){ 6 if(Board[x][y]!=c){ 7 return 0; 8 } 9 x+=dx; 10 y+=dy; 11 } 12 return 1; 13 } 14 bool win(char a){ 15 for(int i=0;i<3;i++){ 16 if(check(0,i,1,0,a)){ 17 return 1; 18 } 19 if(check(i,0,0,1,a)){ 20 return 1; 21 } 22 } 23 if(check(0,0,1,1,a)){ 24 return 1; 25 } 26 if(check(0,2,1,-1,a)){ 27 return 1; 28 } 29 return 0; 30 } 31 bool validTicTacToe(vector<string>& board) { 32 33 34 int X=0; 35 int O=0; 36 int len=board.size(); 37 for(int i=0;i<len;i++){ 38 39 for(int j=0;j<3;j++){ 40 41 Board[i][j]=board[i][j]; 42 43 if(Board[i][j]=='X'){ 44 X++; 45 } 46 if(Board[i][j]=='O'){ 47 O++; 48 } 49 } 50 // Str=""; 51 } 52 if(X!=O&&O+1!=X){ 53 return false; 54 } 55 int x=win('X'); 56 int o=win('O'); 57 if(o+x>=2){ 58 return false; 59 } 60 // for(int i=0;i<3;i++){ 61 // for(int j=0;j<3;j++){ 62 // cout<<Board[i][j]; 63 // } 64 // cout<<endl; 65 // } 66 if(x){ 67 return X==(O+1); 68 } 69 if(o){ 70 //cout<<o<<endl; 71 return X==O; 72 } 73 return true; 74 } 75 };