|
| 1 | +from collections import deque |
| 2 | +def solve(): |
| 3 | + n, m, s, dn = map(int, input().split()) # n = no. of vertices, m = no. of edges, s = start node, dn = destination node |
| 4 | + |
| 5 | + if s == dn: |
| 6 | + print(0); print(s) # edge case |
| 7 | + if m > 0: |
| 8 | + u_nodes = input() |
| 9 | + v_nodes = input() |
| 10 | + return |
| 11 | + |
| 12 | + u_nodes = list(map(int, input().split())) if m > 0 else [] |
| 13 | + v_nodes = list(map(int, input().split())) if m > 0 else [] |
| 14 | + |
| 15 | + #adj list_____________________________________________________________________________________ |
| 16 | + |
| 17 | + adj = [[] for _ in range(n + 1)] # 1-indexed adjacency list as 1st vertex is 1 |
| 18 | + |
| 19 | + for i in range(m): # Read m edges (u, v each) and build the adj. list |
| 20 | + u = u_nodes[i]; v = v_nodes[i] |
| 21 | + adj[u].append(v); adj[v].append(u) |
| 22 | + |
| 23 | + for i in range(1, n + 1): |
| 24 | + adj[i].sort() # Sort the adjacency list for consistent traversal order |
| 25 | + |
| 26 | + #initialize BFS_____________________________________________________________________________________ |
| 27 | + |
| 28 | + color = [0] * (n + 1) # All vertices are initially white; 0: unvisited/white, 1: visited/Gray; 1-indexed |
| 29 | + color[s] = 1 # Mark the start node as Gray |
| 30 | + |
| 31 | + parent = [-1] * (n + 1) # To store the parent of each node |
| 32 | + |
| 33 | + d = [-1] * (n + 1) # To store the distance from the start node |
| 34 | + d[s] = 0 # Distance from start node to itself is 0 |
| 35 | + |
| 36 | + found = False # Flag to check if the destination node is found |
| 37 | + |
| 38 | + queue = deque() # Initialize the queue |
| 39 | + queue.append(s) # initially add the start node to the queue |
| 40 | + |
| 41 | + #BFS loop_____________________________________________________________________________________ |
| 42 | + |
| 43 | + while queue: |
| 44 | + u = queue.popleft() |
| 45 | + |
| 46 | + if u == dn: # If the destination node is found |
| 47 | + found = True |
| 48 | + break |
| 49 | + |
| 50 | + for v in adj[u]: |
| 51 | + if color[v] == 0: # if color is white (unvisited) |
| 52 | + color[v] = 1 # Mark the neighbor as Gray |
| 53 | + parent[v] = u |
| 54 | + d[v] = d[u] + 1 |
| 55 | + queue.append(v) |
| 56 | + |
| 57 | + #output_____________________________________________________________________________________ |
| 58 | + |
| 59 | + if not found: |
| 60 | + print(-1) |
| 61 | + else: |
| 62 | + print(d[dn]) # Print the distance from start node to destination node |
| 63 | + |
| 64 | + path = [] |
| 65 | + curr = dn |
| 66 | + while curr != -1: |
| 67 | + path.append(curr) |
| 68 | + curr = parent[curr] |
| 69 | + |
| 70 | + path.reverse() # Reverse the path to get the correct order |
| 71 | + print(" ".join(map(str, path))) # Print the path from start node to destination node |
| 72 | + |
| 73 | +solve() |
0 commit comments