Single source
- Algorithms course
- Advanced
- Lesson 29/56
- 4 min
Shortest path from one source to all vertices.
Single source
Dijkstra's algorithm finds shortest paths from a single source node to all other nodes in a graph. It requires non-negative weights.
The output is a distance array: dist[i] is the shortest distance from the source to i. The algorithm fails if there are negative edges.
Adjacency list
The graph is represented as a list of neighbors for each node. Each element is a (neighbor, weight) pair; for example graph[0] = [(1, 4), (2, 1)].
This representation saves space in sparse graphs and lets Dijkstra run efficiently.
Practice init_graph function
Write init_graph(). Return the adjacency list. Print it with print(init_graph()).
Starter code
def init_graph():
# Return adjacency listSample solution
def init_graph():
# Return adjacency list
return [[(1, 4), (2, 1)], [(3, 1)], [(1, 2), (3, 5)], []]
print(init_graph())Expected output
[[(1, 4), (2, 1)], [(3, 1)], [(1, 2), (3, 5)], []]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which case does Dijkstra not support?
- Negative weights Correct answer
- Non-negative weights
- Zero weights
- Integer weights
Explanation: Dijkstra does not support negative weights.
2 Edge weight
graph[0] = [(1, ____)]
graph[0] = [(1, 4)]
Explanation: 4 is right.
3 Single source: match the terms
| Term | Meaning |
|---|---|
graph[0] |
[(1,4),(2,1)] |
graph[1] |
[(3,1)] |
graph[2] |
[(1,2),(3,5)] |
graph[3] |
[] |