#1 India's Top IT Training Institute

×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
Graph Algorithms

Dijkstra's Algorithm in Data Structure

Dijkstra's Algorithm finds the shortest path from a single source vertex to all other vertices in a graph with non-negative edge weights.

How It Works

  • Initialize the distance to the source as 0 and all others as infinity.
  • Use a priority queue to repeatedly select the unvisited vertex with the smallest known distance.
  • Relax all edges from that vertex — update neighbor distances if a shorter path is found.
  • Mark the vertex as visited and repeat until all vertices are processed.
import heapq

def dijkstra(graph, source):
    distances = {node: float('inf') for node in graph}
    distances[source] = 0
    pq = [(0, source)]

    while pq:
        current_dist, node = heapq.heappop(pq)
        if current_dist > distances[node]:
            continue
        for neighbor, weight in graph[node]:
            distance = current_dist + weight
            if distance < distances[neighbor]:
                distances[neighbor] = distance
                heapq.heappush(pq, (distance, neighbor))

    return distances

Complexity

ImplementationTime
Adjacency matrix (no heap)O(V²)
Adjacency list with binary heapO((V + E) log V)

Limitations

Dijkstra's Algorithm does not work correctly with negative edge weights; the Bellman-Ford algorithm should be used instead in that case.

Applications

  • GPS navigation and route planning.
  • Network routing protocols (e.g., OSPF).
  • Flight/travel booking systems to find the cheapest or fastest route.

Ready to master Data Structures & Algorithms?

Learn DSA hands-on with mentor-led sessions, real interview practice, and placement support.

Explore Course