LeetCode 794 Valid Tic-Tac-Toe State (Python)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010870545/article/details/82985176
class Solution(object):
    def validTicTacToe(self, board):
        """
        :type board: List[str]
        :rtype: bool
        """
        # count_x - count_o  in [0,1]
        # only one reach 
        xxx="XXX"
        ooo="OOO"
        count_x=count_o=count_o3=count_x3=0
        for s in board:
            if s == ooo:
                count_o3+=1
            elif s==xxx:
                count_x3+=1
        for c in range(3):
            s = ''.join(board[r][c] for r in range(3))
            if s == ooo:
                count_o3+=1
            elif s==xxx:
                count_x3+=1
        s= ''.join(board[i][i] for i in range(3))
        if s == ooo:
            count_o3+=1
        elif s==xxx:
            count_x3+=1

        s=''.join(board[i][2-i] for i in range(3))
        if s == ooo:
            count_o3+=1
        elif s==xxx:
            count_x3+=1

        for row in board:
            for x in row:
                if x=='X':
                    count_x+=1
                elif x=='O':
                    count_o+=1
        # if count_x3>=1 and count_o3>=1:
        #     return False
        if count_o3>=1 and count_x!=count_o:
            return False
        if count_x3>=1 and count_x!=count_o+1:
            return False
            
        if (count_x-count_o) not in [0,1]:
            return False
                
        return True

猜你喜欢

转载自blog.csdn.net/u010870545/article/details/82985176