leetcode:有效的井字游戏

leetcode:有效的井字游戏,第1张

leetcode:有效的井字游戏


思路:
多种情况的判断
逻辑详细看注释

代码:

class Solution:
    def validTicTacToe(self, board: List[str]) -> bool:
        # 第一个是X
        # X总是等于O或等于O + 1
        # 不可以X O 同时胜利
        cnt = 0
        x_cnt = 0
        o_cnt = 0
        for row in board:
            for item in row:
                if item == 'X':
                    x_cnt += 1
                    cnt += 1
                elif item == 'O':
                    o_cnt += 1
                    cnt += 1
        
        #第一个必须X        
        # X = O or X = O + 1
        if x_cnt > o_cnt + 1 or x_cnt < o_cnt:
            return False

        # 判断X或O是否获胜
        x_win = False
        o_win = False

        # 把获胜的八种情况列出来
        eight_situations = []
        # 三行
        for row in board:
            eight_situations.append(row)

        # 三列
        for j in range(3):
            temp = ""
            for i in range(3):
                temp += board[i][j]
            eight_situations.append(temp)
        
        # 两对角
        temp1 = ""
        temp2 = ""
        for i in range(3):
            temp1 += board[i][i]
            temp2 += board[i][2 - i]
        eight_situations.append(temp1)
        eight_situations.append(temp2)

        if 'XXX' in eight_situations:
            x_win = True
        if 'OOO' in eight_situations:
            o_win = True

        # 不可以同时获胜
        if x_win is True and o_win is True:
            return False
        
        # X赢了之后 O不可以动
        if x_win is True and x_cnt == o_cnt:
            return False
        
        # O赢了之后 X不可以动
        if o_win is True and x_cnt == o_cnt + 1:
            return False

        return True
        

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5651238.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-16
下一篇2022-12-16

发表评论

登录后才能评论

评论列表(0条)

    保存