代码随想录刷题第三十天| 332.重新安排行程 ● 51. N皇后 ● 37. 解数独 ● 总结

代码随想录刷题第三十天

重新安排行程 (LC 332)

题目思路:

在这里插入图片描述
在这里插入图片描述

代码实现:

class Solution:
    def __init__(self):
        self.path = ['JFK']

    def findItinerary(self, tickets: List[List[str]]) -> List[str]:
        # targets is a dictionary of list which stores the mapping between 出发地和目的地
        targets = defaultdict(list)
        for ticket in tickets:
            targets[ticket[0]].append(ticket[1])
        # sort the values of the dictionary
        for destination in targets.values():
            destination.sort()
        
        self.backtracking(targets, len(tickets))
        return self.path       

    def backtracking(self, targets, ticketnum):
        if len(self.path) == ticketnum+1:
            return True
        
        cur = self.path[-1]
        for i, airport in enumerate(targets[cur]):
            targets[cur].pop(i)
            self.path.append(airport)
            nextbool = self.backtracking(targets, ticketnum)
            if nextbool:
                return True
            self.path.pop()
            targets[cur].insert(i, airport)
        return False

N皇后 (LC 51)

题目思路:

在这里插入图片描述
在这里插入图片描述

代码实现:

class Solution:
    def __init__(self):
        self.result = []

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

    def backtracking(self, n, row, path):
        if row == n:
            self.result.append(path[:])
            return
        
        for col in range(n):
            if self.isvalid(row, col, n, path):
                path[row] = path[row][:col] + 'Q' + path[row][col+1:]
                self.backtracking(n, row+1, path)
                path[row] = path[row][:col] + '.' + path[row][col+1:]
    
    def isvalid(self, row, col, n, path):
        #检查列
        for i in range(row):
            if path[i][col] == 'Q':
                return False
        # 检查135度
        i = row-1
        j = col-1
        while i>=0 and j>=0:
            if path[i][j] == 'Q':
                return False
            i-=1
            j-=1
        # 检查45度
        i = row-1
        j = col+1
        while i>=0 and j<n:
            if path[i][j] == 'Q':
                return False
            i-=1
            j+=1
        return True

解数独 (LC 37)

题目思路:

在这里插入图片描述
在这里插入图片描述

代码实现:

class Solution:
    def solveSudoku(self, board: List[List[str]]) -> None:
        """
        Do not return anything, modify board in-place instead.
        """
        mybool = self.backtracking(board)
        return mybool

    
    def backtracking(self, board):
        for i in range(9):
            for j in range(9):
                if board[i][j] !='.':
                    continue
                for k in range(1,10):
                    if self.isvalid(board, i, j, k):
                        board[i] = board[i][:j]+[str(k)]+board[i][j+1:]
                        nextbool = self.backtracking(board)
                        if nextbool:
                            return True
                        board[i] = board[i][:j]+['.']+board[i][j+1:]
                return False
        return True

    def isvalid(self, board, i, j, k):
        for row in range(9):
            if board[row][j] == str(k):
                return False
        for col in range(9):
            if board[i][col] == str(k):
                return False
        
        for row in range(3*(i//3), 3*(i//3)+3):
            for col in range(3*(j//3), 3*(j//3)+3):
                if board[row][col] == str(k):
                    return False
        
        return True
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值