Leetcode 794. Valid Tic-Tac-Toe State

文章作者:Tyan
博客:noahsnail.com  |  优快云  |  简书

1. Description

Valid Tic-Tac-Toe State

2. Solution

**解析:**Version 1,判断游戏合不合法,主要分为下面几个方面:

  1. 由于X先放,轮流放置,因此X的数量永远大于等于O的数量。
  2. 由于是轮流放置,因此二者的数量差值最大为1。
  3. X先结束游戏时,此时X的数量等于O的数量加1。
  4. O先结束游戏时,此时X的数量等于O的数量。
    根据上述条件依次判断即可。
  • Version 1
class Solution:
    def validTicTacToe(self, board: List[str]) -> bool:
        x_count = 0
        o_count = 0
        for line in board:
            for ch in line:
                if ch == 'X':
                    x_count += 1
                elif ch == 'O':
                    o_count += 1
        if o_count > x_count or x_count > o_count + 1:
            return False
        if x_count == o_count and self.isGameOver(board, 'X'):
            return False
        if x_count == o_count + 1 and self.isGameOver(board, 'O'):
            return False

        return True


    def isGameOver(self, board: List[str], ch: str) -> bool:
        # Check rows
        for i in range(3):
            if board[i][0] == ch and board[i][0] == board[i][1] and board[i][1] == board[i][2]:
                return True

        # Check columns
        for i in range(3):
            if board[0][i] == ch and board[0][i] == board[1][i] and board[1][i] == board[2][i]:
                return True

        # Check diagonals
        if board[1][1] == ch and ((board[0][0] == board[1][1] and board[1][1] == board[2][2]) or
            (board[0][2] == board[1][1] and board[1][1] == board[2][0])):
                return True
        return False

Reference

  1. https://leetcode.com/problems/valid-tic-tac-toe-state/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值