Given a weighted graph and a start and goal node, find the lowest-cost path from start to goal using Uniform Cost Search (UCS). UCS is equivalent to Dijkstra’s algorithm for graphs with non-negative weights.
graph LR;
A(1) -->|3| B(2)
A -->|1| C(3)
B -->|3| D(4)
C -->|1| D
D -->|3| G(5)
C -->|2| G
S(0) -->|1| A
S -->|12| G
1
2
3
4
5
6
7
8
9
10
11
12
13
Input:
n =6adj =[[(1,1),(5,12)],#0: S -> A(1), G(12)[(2,3),(3,1)],#1: A -> B(3), C(1)[(4,3)],#2: B -> D(3)[(4,1),(5,2)],#3: C -> D(1), G(2)[(5,3)],#4: D -> G(3)[]#5: G
]start, goal =0,5Output: 4Explanation: Graph as shown above. UCS finds the lowest-cost path from 0 to 5, which isthis one:0→1→3→5, expanding nodes in order of cumulative cost.
Here is how the search will look like:
graph TD;
S(0) ---|1| A(1)
S(0) ---|12| G(5)
A(1) ---|1| B(2)
A(1) ---|3| C(3)
B ---|3| D(4) ---|3| G2(5)
C ---|1| D2(4) ---|3| G3(5)
C ---|2| G4(5)
UCS always expands the node with the lowest cumulative cost so far, guaranteeing the optimal path in graphs with non-negative weights. It uses a priority queue to manage the frontier.