LeetCode算法刷题(python) Day32|07回溯算法|332.重新安排行程、51. N皇后、37. 解数独

LeetCode 332. 重新安排行程

力扣题目链接

第一次做的时候超时了,

class Solution:
    def findItinerary(self, tickets: List[List[str]]) -> List[str]:
        starts = [i[0] for i in tickets]
        ends = [i[1] for i in tickets]
        used_s = [0] * len(tickets)
        used_e = [0] * len(tickets)

        result = []
        self.dfs(result, ['JFK'], starts, ends, used_s, used_e, 'JFK')
        result.sort()
        return result[0]
    
    def dfs(self, result, path, starts, ends, used_s, used_e, start):
        if len(path) == len(starts) + 1:
            result.append(path[:])
            return
        
        for i in range(len(starts)):
            if starts[i] != start or used_s[i] == 1:
                continue
            # path.append(starts[i])
            path.append(ends[i])
            used_s[i] = 1
            used_e[i] = 1
            self.dfs(result, path, starts, ends, used_s, used_e, ends[i])
            path.pop()
            # path.pop()
            used_s[i] = 0
            used_e[i] = 0

其实只需先排序,一旦找到满足条件的路径即可返回,不用继续搜索了,一定是最小的。最开始没有考虑清楚这个排序。

class Solution:
    def findItinerary(self, tickets: List[List[str]]) -> List[str]:
        tickets.sort()
        used = [0] * len(tickets)
        result = []
        self.dfs(result, ['JFK'], tickets, used, 'JFK')
        return result[0]
    
    def dfs(self, result, path, tickets, used, start):
        if len(path) == len(tickets) + 1:
            result.append(path[:])
            return True
        
        for i in range(len(tickets)):
            if tickets[i][0] == start and used[i] == 0:
                path.append(tickets[i][1])
                used[i] = 1
                state = self.dfs(result, path, tickets, used, tickets[i][1])
                if state:
                    return
                path.pop()
                used[i] = 0

LeetCode 51. N皇后

力扣题目链接
本题可以每次在一行中填皇后,递归n次。在每一行填皇后的时候,有n个选择,判断当前选择是否合法,如果合法填进去之后再递归下一行。

class Solution:
    def solveNQueens(self, n: int) -> List[List[str]]:
        result = []
        chessboard = [['.'] * n for _ in range(n)]
        self.dfs(result, chessboard, n, 0)
        return result

    def dfs(self, result, chessboard, n, row):
        if row == n:
            result.append([''.join(i) for i in chessboard])
            return

        for i in range(n):
            if self.isValid(chessboard, n, row, i):
                chessboard[row][i] = 'Q'
                self.dfs(result, chessboard, n, row+1)
                chessboard[row][i] = '.'
    
    def isValid(self, chessboard, n, row, col):
        if 'Q' in chessboard[row]:
            return False
        if 'Q' in [i[col] for i in chessboard]:
            return False
        for delta_r, delta_c in [(-1, -1), (-1, 1), (1, -1), (1, 1)]:
            r, c = row, col
            while (r >= 0 and r < n) and (c >= 0 and c < n):
                if chessboard[r][c] == 'Q':
                    return False
                r += delta_r
                c += delta_c
        return True

LeetCode 37. 解数独

力扣题目链接

超时答案

class Solution:
    def solveSudoku(self, board: List[List[str]]) -> None:
        """
        Do not return anything, modify board in-place instead.
        """
        self.backtracking(board, 0, 0, [0]*9)
    
    def backtracking(self, board, row, col, used):
        if row > 8:
            return

        if board[row][col] == '.':
            for num in range(9):
                if used[num] == 1:
                    continue
                if self.isValid(board, row, col, str(num+1)):
                    board[row][col] = str(num+1)
                    used[num] == 1
                    if col == 8:
                        self.backtracking(board, row+1, 0, [0]*9)
                    else:
                        self.backtracking(board, row, col+1, used)
                    board[row][col] = '.'
                    used[num] == 0
        else:
            if col == 8:
                self.backtracking(board, row+1, 0, used)
            else:
                self.backtracking(board, row, col+1, [0]*9)

    
    def isValid(self, board, row, col, num):
        if num in board[row]:
            return False
        if num in [row[col] for row in board]:
            return False
        
        r = (row // 3) * 3
        c = (col // 3) * 3

        sub_board = [row[c:c+3] for row in board][r:r+3]

        for i in sub_board:
            if num in sub_board:
                return False
        return True
            
       

修改答案,其实就是每个格往里填,符合条件就填,不符合就返回False

class Solution:
    def solveSudoku(self, board: List[List[str]]) -> None:
        """
        Do not return anything, modify board in-place instead.
        """
        self.backtracking(board)
    
    def backtracking(self, board):
        for i in range(len(board)):
            for j in range(len(board[0])):
                if board[i][j] != '.': continue
                for k in range(1, 10):
                    if self.isValid(board, i, j, k):
                        board[i][j] = str(k)
                        if self.backtracking(board): return True
                        board[i][j] = '.'
                return False
        return True
    
    def isValid(self, board, row, col, num):
        num = str(num)
        if num in board[row]:
            return False
        if num in [row[col] for row in board]:
            return False
        
        r = (row // 3) * 3
        c = (col // 3) * 3

        for i in range(r, r+3):
            for j in range(c, c+3):
                if board[i][j] == num:
                    return False
        return True
            
            

今日毕!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值