-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbed_test.py
More file actions
224 lines (168 loc) · 6.46 KB
/
bed_test.py
File metadata and controls
224 lines (168 loc) · 6.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
# from collections import deque
# from typing import List
# class Solution:
# def shortestPathQueries(self, n: int, queries: List[List[int]]) -> List[int]:
# # Build initial graph: i -> i+1
# graph = [[] for _ in range(n)]
# for i in range(n - 1):
# graph[i].append(i + 1)
# def bfs():
# dist = [-1] * n
# dist[0] = 0
# q = deque([0])
# while q:
# u = q.popleft()
# if u == n - 1:
# return dist[u]
# for v in graph[u]:
# if dist[v] == -1:
# dist[v] = dist[u] + 1
# q.append(v)
# return -1
# ans = []
# for u, v in queries:
# graph[u].append(v)
# ans.append(bfs())
# return ans
# # Example usage
# n = 5
# queries = [[2, 4], [0, 2], [0, 4]]
# solution = Solution()
# print(solution.shortestPathQueries(n, queries)) # [3, 2, 1]
# Import necessary libraries
# import heapq
# n = 5
# # Define the graph with default roads
# def init_graph(n):
# graph = {i: [(i + 1, 1)] for i in range(n - 1)}
# graph[n - 1] = [] # The last city has no outgoing roads
# return graph
# # Function to perform Dijkstra's algorithm
# def dijkstra(graph, start, end):
# distances = [float('inf')] * n
# distances[start] = 0
# priority_queue = [(0, start)]
# while priority_queue:
# current_distance, current_node = heapq.heappop(priority_queue)
# if current_distance > distances[current_node]:
# continue
# for neighbor, weight in graph[current_node]:
# distance = current_distance + weight
# if distance < distances[neighbor]:
# distances[neighbor] = distance
# heapq.heappush(priority_queue, (distance, neighbor))
# return distances[end]
# # Test the initial approach
# def test_initial_approach():
# n = 5
# queries = [[2, 4], [0, 2], [0, 4]]
# expected_output = [3, 2, 1]
# graph = init_graph(n)
# results = []
# for u, v in queries:
# if u not in graph:
# graph[u] = []
# graph[u].append((v, 1))
# results.append(dijkstra(graph, 0, n - 1))
# assert results == expected_output, f"Expected output: {expected_output}, but got: {results}"
# print("Test passed!")
# test_initial_approach()
# Add more edges to the graph
# graph = {
# 0: [(1, 1), (2, 1)],
# 1: [(3, 1)],
# 2: [(3, 1)],
# 3: [(4, 1)],
# 4: []
# }
# # Function to perform Dijkstra's algorithm
# def dijkstra(graph, start, end):
# distances = [float('inf')] * len(graph)
# distances[start] = 0
# priority_queue = [(0, start)]
# while priority_queue:
# current_distance, current_node = heapq.heappop(priority_queue)
# if current_distance > distances[current_node]:
# continue
# for neighbor, weight in graph[current_node]:
# distance = current_distance + weight
# if distance < distances[neighbor]:
# distances[neighbor] = distance
# heapq.heappush(priority_queue, (distance, neighbor))
# return distances[end]
# # Test the Dijkstra's algorithm with the updated graph
# shortest_paths = [dijkstra(graph, 0, n - 1) for _ in range(len(queries))]
# print(shortest_paths)
# from typing import List
# import heapq
# class Solution:
# def shortestDistanceAfterQueries(self, n: int, queries: List[List[int]]) -> List[int]:
# def dijkstra(graph, start, end):
# distances = [float('inf')] * n
# distances[start] = 0
# priority_queue = [(0, start)]
# while priority_queue:
# current_distance, current_node = heapq.heappop(priority_queue)
# if current_distance > distances[current_node]:
# continue
# for neighbor, weight in graph[current_node]:
# distance = current_distance + weight
# if distance < distances[neighbor]:
# distances[neighbor] = distance
# heapq.heappush(priority_queue, (distance, neighbor))
# return distances[end]
# # Initialize the graph with the default roads
# graph = {i: [(i + 1, 1)] for i in range(n - 1)}
# graph[n - 1] = [] # The last city has no outgoing roads
# # Process each query
# results = []
# for u, v in queries:
# if u not in graph:
# graph[u] = []
# graph[u].append((v, 1))
# results.append(dijkstra(graph, 0, n - 1))
# return results
# n=5
# queries=[[2,4],[0,2],[0,4]]
# # Initial graph: 0→1→2→3→4 (path length = 4)
# from collections import deque
# def bfs_shortest_path(graph, start, end, n):
# """Find shortest path using BFS"""
# distances = [-1] * n
# distances[start] = 0
# queue = deque([start])
# while queue:
# node = queue.popleft()
# if node == end:
# return distances[end]
# for neighbor in graph[node]:
# if distances[neighbor] == -1:
# distances[neighbor] = distances[node] + 1
# queue.append(neighbor)
# return distances[end]
# n = 5
# graph = {i: [] for i in range(n)}
# for i in range(n - 1):
# graph[i].append(i + 1)
# print("Initial graph:", graph)
# print("Initial shortest path from 0 to 4:", bfs_shortest_path(graph, 0, n-1, n))
# graph[2].append(4)
# print("\nAfter adding 2→4:")
# print("Shortest path:", bfs_shortest_path(graph, 0, n-1, n))
# graph[0].append(2)
# print("\nAfter adding 0→2:")
# print("Shortest path:", bfs_shortest_path(graph, 0, n-1, n))
# graph[0].append(4)
# print("\nAfter adding 0→4:")
# print("Shortest path:", bfs_shortest_path(graph, 0, n-1, n))
# Case when the longest_common_prefix is already defined above *****
# Complete solution testing
# test_cases = [
# (["flower", "flow", "flight"], "fl"),
# (["dog", "racecar", "car"], ""),
# (["interspecies", "interstellar", "interstate"], "inters")
# ]
# for strs, expected in test_cases:
# result = longest_common_prefix(strs)
# assert result == expected, f"Expected {expected}, but got {result} for input {strs}"
# print(f"Test passed for input {strs}: {result}")