码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2019-12-02 19:11:51      阅读:70      评论:0      收藏:0      [点我收藏+]

标签:ret   自己   board   else   com   描述   pat   self   filter   

题目描述:

技术图片

 

 技术图片

 

 技术图片

 

 自己的提交:

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-找出井字棋的获胜者

标签:ret   自己   board   else   com   描述   pat   self   filter   

原文地址:https://www.cnblogs.com/oldby/p/11972482.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!