---
# System prepended metadata

title: 0794. Valid Tic-Tac-Toe State
tags: [Leetcode, FaceBook, Medium]

---

# 0794. Valid Tic-Tac-Toe State
###### tags: `Leetcode` `FaceBook` `Medium`
Link: https://leetcode.com/problems/valid-tic-tac-toe-state/
## 思路
就模拟一遍就好了
以下情况是invalid
- player1放的棋子数量不等于player2放的数量也不等于player2数量+1
- player1赢了但是player2在player1赢了之后又放了棋子，也就是player1 count = player2 count
- player2赢了但是player1 count = player2 count+1
## Code
```java=
class Solution {
    int[] row = new int[3];
    int[] col = new int[3];
    int diagonal1=0, diagonal2=0;
    int count1=0, count2=0;
    
    public boolean validTicTacToe(String[] board) {
        for(int i = 0;i < board.length;i++){
            String r = board[i];
            for(int j = 0;j < r.length();j++){
                if(r.charAt(j)==' ') continue;
                int player = r.charAt(j)=='X'?1:-1;
                row[i] += player;
                col[j] += player;
                if(i==j) diagonal1 += player;
                if(i+j==2) diagonal2 += player;
                if(player==1) count1++;
                else if(player==-1) count2++;
            }
        }
        
        if(!(count1==count2||count1==count2+1)){
            return false;
        }
        
        if(ifwin(1) && count1==count2){
            return false;
        }
        
        if(ifwin(-1) && count1!=count2){
            return false;
        }
        
         return true;
    }
    
    public boolean ifwin(int player){
        for(int i = 0;i < 3;i++){
            if(row[i] == 3*player || col[i] == 3*player){
                return true;
            }
        }
        if(diagonal1 == 3*player || diagonal2 == 3*player){
            return true;
        }
        return false;
    }
}
```