DSA SectionEasy

Dijkstra

Detailed guide and Python implementation for the 'Dijkstra' problem.

Problem Statement

Easy

Write a function dijkstra(graph, start) that calculates the shortest path from a starting node start to all other nodes in a weighted graph. The graph is represented as an adjacency list of dictionaries, where graph[u][v] is the weight of the directed edge from u to v. Return a dictionary of shortest distances.

Constraints
  • 1 <= V <= 1000
  • 0 <= E <= 5000
  • Weights are non-negative integers.

Examples

Example 1
Input
graph = {0: {1: 4, 2: 1}, 1: {3: 1}, 2: {1: 2, 3: 5}, 3: {}}, start = 0
Output
{0: 0, 1: 3, 2: 1, 3: 4}
Explanation

Shortest distance from 0 to 1 is 3 (via 0->2->1).

Need a Hint?
Consider using Graphs-specific data structures like sets or heaps.
Edge Cases to Watch
  • Empty input structures
  • Single element inputs
  • Large numerical bounds

Ready to Solve?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Open in Editor

Recommended Python Resources

Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.