How to shorten generating a graph when trying to use breadth first search?

Im not sure how to explain this. Basically I am trying to do Leetcode problem “752. open the lock”

My solution was to use breadth first search algorithm. Basically:

  1. Generate the 10,000 possible combination graph like so
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>graph{
0000:{0001,0010,0100,...9000},
.
.
.
9999:{9990,9909...0999}
}
</code>
<code>graph{ 0000:{0001,0010,0100,...9000}, . . . 9999:{9990,9909...0999} } </code>
graph{
0000:{0001,0010,0100,...9000},
.
.
.
9999:{9990,9909...0999}
}
  1. use breadth first search to print out every single possible paths from start to end, save those paths into a 2d array.
  2. as per the target and deadlocks start filtering every path
  • take out all those paths with deadlocks
  • take out all those paths where target is not the final value
  1. get the length of the shortest path, minus 1 and then return it

When manually testing the testcases, it seems like my program works. But generating the 10,000 possible combinations took so long that when I submit, Leetcode gives time limit exceed error.

When using BFS, shouldn’t there be an existing graph? But when generating the graph it takes too long to compute. So how do I go about generating a graph during the BFS dynamically, which could shorten the time to compute

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>class Solution:
@staticmethod
def generate_lock_graph():
# Initialize the lock graph
lock_graph = {}
# Generate all possible combinations of lock digits
for i in range(10):
for j in range(10):
for k in range(10):
for l in range(10):
node = f"{i}{j}{k}{l}" # Create a lock combination node
neighbors = [] # Initialize the list of neighboring nodes
# Generate all possible moves for the current lock combination
for digit in range(4):
# Generate a new lock combination by incrementing the digit
new_combination = list(node)
new_combination[digit] = str((int(new_combination[digit]) + 1) % 10)
neighbors.append("".join(new_combination))
# Generate a new lock combination by decrementing the digit
new_combination = list(node)
new_combination[digit] = str((int(new_combination[digit]) - 1) % 10)
neighbors.append("".join(new_combination))
lock_graph[node] = neighbors
return lock_graph
@staticmethod
def bfs(graph, start):
global explored
global queue
global possiblePaths
explored = []
queue = [[start]]
possiblePaths = [[start]]
while queue: # Creating loop to visit each node
# Get current node
path = queue.pop(0)
node = path[-1]
if node not in explored:
neighbours = graph[node]
for neighbour in neighbours:
new_path = list(path)
new_path.append(neighbour)
possiblePaths.append(new_path)
queue.append(new_path)
explored.append(node)
# print(possiblePaths)
return possiblePaths
def openLock(self, deadends: List[str], target: str) -> int:
graph = self.generate_lock_graph() #generate the graph
allpaths = self.bfs(graph,"0000") #start bfs, give all possible path from start to finish
allpaths = [path for path in allpaths if not any(deadend in path for deadend in deadends)] # remove all paths with deadends
# allpaths = [path for path in allpaths if target in path] # remove all paths without the target
allpaths = [path for path in allpaths if path[-1] == target] # remove all paths where target is not the final value
# print(allpaths)
if len(allpaths) == 0: # return -1 if no possible paths
return -1
else:
return len(allpaths[allpaths.index(min(allpaths,key=len))]) - 1 # minus one to remove the first node, get the shortest list (shortest path)
solution = Solution()
# solution.bfs(graph,'0000')
deadends = ["0201","0101","0102","1212","2002"]
target = "0202"
print(solution.openLock(deadends,target))
</code>
<code>class Solution: @staticmethod def generate_lock_graph(): # Initialize the lock graph lock_graph = {} # Generate all possible combinations of lock digits for i in range(10): for j in range(10): for k in range(10): for l in range(10): node = f"{i}{j}{k}{l}" # Create a lock combination node neighbors = [] # Initialize the list of neighboring nodes # Generate all possible moves for the current lock combination for digit in range(4): # Generate a new lock combination by incrementing the digit new_combination = list(node) new_combination[digit] = str((int(new_combination[digit]) + 1) % 10) neighbors.append("".join(new_combination)) # Generate a new lock combination by decrementing the digit new_combination = list(node) new_combination[digit] = str((int(new_combination[digit]) - 1) % 10) neighbors.append("".join(new_combination)) lock_graph[node] = neighbors return lock_graph @staticmethod def bfs(graph, start): global explored global queue global possiblePaths explored = [] queue = [[start]] possiblePaths = [[start]] while queue: # Creating loop to visit each node # Get current node path = queue.pop(0) node = path[-1] if node not in explored: neighbours = graph[node] for neighbour in neighbours: new_path = list(path) new_path.append(neighbour) possiblePaths.append(new_path) queue.append(new_path) explored.append(node) # print(possiblePaths) return possiblePaths def openLock(self, deadends: List[str], target: str) -> int: graph = self.generate_lock_graph() #generate the graph allpaths = self.bfs(graph,"0000") #start bfs, give all possible path from start to finish allpaths = [path for path in allpaths if not any(deadend in path for deadend in deadends)] # remove all paths with deadends # allpaths = [path for path in allpaths if target in path] # remove all paths without the target allpaths = [path for path in allpaths if path[-1] == target] # remove all paths where target is not the final value # print(allpaths) if len(allpaths) == 0: # return -1 if no possible paths return -1 else: return len(allpaths[allpaths.index(min(allpaths,key=len))]) - 1 # minus one to remove the first node, get the shortest list (shortest path) solution = Solution() # solution.bfs(graph,'0000') deadends = ["0201","0101","0102","1212","2002"] target = "0202" print(solution.openLock(deadends,target)) </code>
class Solution:
    @staticmethod
    def generate_lock_graph():
        # Initialize the lock graph
        lock_graph = {}
        
        # Generate all possible combinations of lock digits
        for i in range(10):
            for j in range(10):
                for k in range(10):
                    for l in range(10):
                        node = f"{i}{j}{k}{l}"  # Create a lock combination node
                        neighbors = []  # Initialize the list of neighboring nodes
                        
                        # Generate all possible moves for the current lock combination
                        for digit in range(4):
                            # Generate a new lock combination by incrementing the digit
                            new_combination = list(node)
                            new_combination[digit] = str((int(new_combination[digit]) + 1) % 10)
                            neighbors.append("".join(new_combination))
                            
                            # Generate a new lock combination by decrementing the digit
                            new_combination = list(node)
                            new_combination[digit] = str((int(new_combination[digit]) - 1) % 10)
                            neighbors.append("".join(new_combination))
                        
                        lock_graph[node] = neighbors
        
        return lock_graph

    @staticmethod
    def bfs(graph, start):
        global explored
        global queue
        global possiblePaths

        explored = []
        queue = [[start]]
        possiblePaths = [[start]]

        while queue:  # Creating loop to visit each node
            # Get current node
            path = queue.pop(0)
            node = path[-1]

            if node not in explored:
                neighbours = graph[node]
                for neighbour in neighbours:
                    new_path = list(path)
                    new_path.append(neighbour)

                    possiblePaths.append(new_path)
                    queue.append(new_path)
                explored.append(node)
        # print(possiblePaths)
        return possiblePaths

    def openLock(self, deadends: List[str], target: str) -> int:
        graph = self.generate_lock_graph() #generate the graph
        allpaths = self.bfs(graph,"0000") #start bfs, give all possible path from start to finish
        allpaths = [path for path in allpaths if not any(deadend in path for deadend in deadends)] # remove all paths with deadends
        # allpaths = [path for path in allpaths if target in path] # remove all paths without the target
        allpaths = [path for path in allpaths if path[-1] == target] # remove all paths where target is not the final value
        # print(allpaths)
        if len(allpaths) == 0: # return -1 if no possible paths
            return -1
        else:
            return len(allpaths[allpaths.index(min(allpaths,key=len))]) - 1 # minus one to remove the first node, get the shortest list (shortest path)
solution = Solution()
# solution.bfs(graph,'0000')
deadends = ["0201","0101","0102","1212","2002"]
target = "0202"
print(solution.openLock(deadends,target))

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật