leetcode-165周赛-1275-找出井字棋的获胜者

Posted 真不知道叫啥好

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode-165周赛-1275-找出井字棋的获胜者相关的知识,希望对你有一定的参考价值。

题目描述:

 

 

 

 

 

 自己的提交:

class Solution:
    def tictactoe(self, moves: List[List[int]]) -> str:
        p = [[0] * 3 for _ in range(3)]
        if len(moves) < 5:
            return "Pending"
        for i in moves[::2]:
            p[i[0]][i[1]] = "X"
        for i in moves[1::2]:
            p[i[0]][i[1]] = "O"
        for i in p:
            if i == ["X","X","X"]:
                return "A"
            if i == ["O","O","O"]:
                return "B"
        for i in zip(p[0],p[1],p[2]):
            if i == ("X","X","X"):
                return "A"
            if i == ("O","O","O"):
                return "B"
        if p[0][0] == p[1][1] == p[2][2] == "X" or p[0][2] == p[1][1] == p[2][0] == "X":
            return "A"
        if p[0][0] == p[1][1] == p[2][2] == "O" or p[0][2] == p[1][1] == p[2][0] == "O":
            return "B"
        for i in p:
            if 0 in i:
                return "Pending"
        return "Draw"

优化:

class Solution(object):
    def tictactoe(self, moves):
        board = [[" "," "," "],[" "," "," "],[" "," "," "]]
        
        def solved():
            diags = [[board[0][0], board[1][1], board[2][2]], [board[0][2], board[1][1], board[2][0]]]
            for row in board + zip(*board) + diags:
                s = set(row)
                if len(s) == 1:
                    a, =s
                    if a in "XO":
                        return "A" if a == "X" else "B"
            return None
        
        p = 0
        for x, y in moves:
            board[x][y] = "XO"[p]
            p^=1
            if solved():
                return solved()
        return "Pending" if len(moves) < 9 else "Draw"

另:

class Solution:
    def tictactoe(self, moves: List[List[int]]) -> str:
        allpath = [
            [[0,0],[0,1],[0,2]],
            [[1,0],[1,1],[1,2]],
            [[2,0],[2,1],[2,2]],
            [[0,0],[1,0],[2,0]],
            [[0,1],[1,1],[2,1]],
            [[0,2],[1,2],[2,2]],
            [[0,0],[1,1],[2,2]],
            [[2,0],[1,1],[0,2]]
        ]
        def test(a):
            for line in allpath:
                if len(list(filter(lambda path: path in a, line))) == 3:
                    return True
            return False

        if test(moves[0::2]):
            return "A"
        elif test(moves[1::2]):
            return "B"
        elif len(moves) == 9:
            return "Draw"
        else:
            return "Pending"

 

以上是关于leetcode-165周赛-1275-找出井字棋的获胜者的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 第 165 场周赛

Leetcode周赛165

LeetCode 5275. 找出井字棋的获胜者 Find Winner on a Tic Tac Toe Game

井字棋算法

leetcode-165周赛-1276-不浪费原料的汉堡制作方案

C++ 井字棋