</>
Skip to content
DSA lessons (42/55)

DSA — Floyd-Warshall Algorithm

What is Dijkstra's Algorithm?

Finds the shortest path from a source to all vertices in a weighted graph.

import heapq

def dijkstra(graph, start):
    distances = {vertex: float('infinity') for vertex in graph}
    distances[start] = 0
    previous = {vertex: None for vertex in graph}
    pq = [(0, start)]
    
    while pq:
        current_dist, current = heapq.heappop(pq)
        
        if current_dist > distances[current]:
            continue
        
        for neighbor, weight in graph[current].items():
            distance = current_dist + weight
            
            if distance < distances[neighbor]:
                distances[neighbor] = distance
                previous[neighbor] = current
                heapq.heappush(pq, (distance, neighbor))
    
    return distances, previous

Time Complexity

OperationComplexity
Using priority queueO((V + E) log V)
Using arrayO(V²)

Applications

  • GPS navigation
  • Network routing
  • Flight scheduling
  • Robotics path planning

Mini Practice

  1. Implement Dijkstra's algorithm
  2. Find shortest path
  3. Reconstruct the path
  4. Handle negative weights (use Bellman-Ford)

Up Next

Continue with Floyd-Warshall — all-pairs shortest path.

Related Topics

Frequently Asked Questions about Floyd-Warshall Algorithm

What is Floyd-Warshall Algorithm in DSA?

Floyd-Warshall Algorithm is a fundamental concept in DSA. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Floyd-Warshall Algorithm?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Floyd-Warshall Algorithm.

Why is Floyd-Warshall Algorithm important in DSA?

Floyd-Warshall Algorithm is essential for DSA development. Understanding this concept will help you write better code and solve real-world problems more effectively.