难度:中等
给你一个字符串数组 boardboardboard 表示井字游戏的棋盘。当且仅当在井字游戏过程中,棋盘有可能达到 boardboardboard 所显示的状态时,才返回 truetruetrue 。
井字游戏的棋盘是一个 3 x 3 数组,由字符 ' ','X' 和 'O' 组成。字符 ' ' 代表一个空位。
以下是井字游戏的规则:
(' ')中。'X' ,而玩家 2 总是放字符 'O' 。'X' 和 'O' 只允许放置在空位中,不允许对已放有字符的位置进行填充。示例 1:

输入:board = ["O "," "," "]
输出:false
解释:玩家 1 总是放字符 "X" 。
示例 2:

输入:board = ["XOX"," X "," "]
输出:false
解释:玩家应该轮流放字符。
示例 3:

输入:board = ["XOX","O O","XOX"]
输出:true
思路:
题目要求判断当前游戏板是否生效,我们思考游戏板生效的规则:
以上条件包含了游戏板生效的全部情况,可以通过反证法验证上面分类条件的正确性。在合法的游戏板,只能有 333 种结果合法,要么没有任何玩家赢,要么玩家一赢,要么玩家二赢。我们可以通过检查两种棋的数量关系即可验证是否有效,同时我们要检测是否存在两个玩家同时赢这种非法情况。
算法实现细节如下:
时间复杂度: O(C)O(C)O(C),由于此题给定的棋盘大小为常数 C=9C=9C=9,因此时间复杂度为常数。
空间复杂度: O(1)O(1)O(1)。
class Solution:def win(self, char, board):return any(board[0][i] == char and board[1][i] == char and board[2][i] == char orboard[i][0] == char and board[i][1] == char and board[i][2] == char for i in range(3)) or \board[0][0] == char and board[1][1] == char and board[2][2] == char or \board[2][0] == char and board[1][1] == char and board[0][2] == chardef validTicTacToe(self, board: List[str]) -> bool:ocount = sum(row.count("O") for row in board)xcount = sum(row.count("X") for row in board)return not (xcount - ocount not in [0, 1] orxcount - ocount != 0 and self.win('O', board) orxcount - ocount != 1 and self.win('X', board))
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/valid-tic-tac-toe-state
上一篇:【什么是区块链】