[leetcode] 794. Valid Tic-Tac-Toe State @ python

版权声明:版权归个人所有,未经博主允许,禁止转载 https://blog.csdn.net/danspace1/article/details/86679190

原题

A Tic-Tac-Toe board is given as a string array board. Return True if and only if it is possible to reach this board position during the course of a valid tic-tac-toe game.

The board is a 3 x 3 array, and consists of characters " ", “X”, and “O”. The " " character represents an empty square.

Here are the rules of Tic-Tac-Toe:

Players take turns placing characters into empty squares (" ").
The first player always places “X” characters, while the second player always places “O” characters.
“X” and “O” characters are always placed into empty squares, never filled ones.
The game ends when there are 3 of the same (non-empty) character filling any row, column, or diagonal.
The game also ends if all squares are non-empty.
No more moves can be played if the game is over.
Example 1:
Input: board = ["O ", " ", " "]
Output: false
Explanation: The first player always plays “X”.

Example 2:
Input: board = [“XOX”, " X ", " "]
Output: false
Explanation: Players take turns making moves.

Example 3:
Input: board = [“XXX”, " ", “OOO”]
Output: false

Example 4:
Input: board = [“XOX”, “O O”, “XOX”]
Output: true
Note:

board is a length-3 array of strings, where each string board[i] has length 3.
Each board[i][j] is a character in the set {" ", “X”, “O”}.
Accepted
8,177
Submissions
28,557

解法

首先我们计算X和O出现的次数, 符合题意的条件是count_x = count_o或者count_x - count_o =1.

然后我们检查是否有哪一方赢了, 题意要求任何一方赢了的话, 另一方不可以再下棋. 那么有三种情况不符合题意: 1) X和O都赢了 2) X赢了, O还在下棋 3) O赢了, X还在下棋. 我们只要排除这些情况即可.

代码

class Solution(object):
    def validTicTacToe(self, board):
        """
        :type board: List[str]
        :rtype: bool
        """
        count_x, count_o = 0, 0
        for row in board:
            count_x += row.count('X')
            count_o += row.count('O')
        if not(count_x == count_o or count_x - count_o == 1):
            return False
        # check winning condition
        def check(mark):
            # check rows
            for row in board:
                if row == mark*3:
                    return True
            # check cols
            for c in range(3):
                col = ''.join([board[r][c] for r in range(3)])
                if col == mark*3:
                    return True
            # check diagnal:
            d1 = board[0][0] + board[1][1] + board[2][2]
            d2 = board[0][2] + board[1][1] + board[2][0]
            if d1 == mark*3 or d2 == mark*3:
                return True
            return False
        win_x, win_o = check('X'), check('O')
        if win_x and win_o:
            return False
        if win_x and count_x == count_o:
            return False
        if win_o and count_x > count_o:
            return False
        return True

猜你喜欢

转载自blog.csdn.net/danspace1/article/details/86679190
今日推荐