0% found this document useful (0 votes)
1 views11 pages

Dijkastra Algorithm

Dijkstra's Algorithm is a well-known method for finding the shortest path between nodes in a graph, developed by Edsger W. Dijkstra in 1956. The document provides a detailed explanation of the algorithm, including its key concepts, step-by-step workings, pseudocode, time and space complexity, and applications in various fields. Additionally, it includes code examples in multiple programming languages such as Python, Java, C++, JavaScript, Rust, and Go.

Uploaded by

Rafe AL Hassan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views11 pages

Dijkastra Algorithm

Dijkstra's Algorithm is a well-known method for finding the shortest path between nodes in a graph, developed by Edsger W. Dijkstra in 1956. The document provides a detailed explanation of the algorithm, including its key concepts, step-by-step workings, pseudocode, time and space complexity, and applications in various fields. Additionally, it includes code examples in multiple programming languages such as Python, Java, C++, JavaScript, Rust, and Go.

Uploaded by

Rafe AL Hassan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Got it, Rafe!

I can’t directly create or export a PDF file for you, but I’ll prepare a well-structured,
detailed write-up on Dijkstra’s Algorithm that you can easily copy into Word, Google Docs, or any
editor and then save/export as a PDF. Here’s a complete version:

Dijkstra’s Algorithm – Detailed Explanation

Introduction

Dijkstra’s Algorithm is one of the most famous algorithms in computer science, used to find the
shortest path between nodes in a graph. It was developed by Edsger W. Dijkstra in 1956 and is
widely applied in:

• Routing protocols (like in computer networks)

• GPS navigation systems

• Game development (pathfinding for AI)

Key Concepts

• Graph: A collection of nodes (vertices) connected by edges.

• Weighted Graph: Each edge has a cost/weight (e.g., distance, time).

• Shortest Path: The path between two nodes with the minimum total weight.

How It Works (Step-by-Step)

1. Initialization:

o Assign a tentative distance value to every node:

▪ Start node = 0

▪ All other nodes = ∞ (infinity)

o Mark all nodes as unvisited.

2. Visit the Current Node:

o For the current node, check all its unvisited neighbors.

o Calculate their tentative distances:

New Distance = Current Distance + Edge Weight

• If the new distance is smaller than the previously recorded distance, update it.

3. Mark as Visited:

o Once all neighbors are checked, mark the current node as visited.
o A visited node will not be checked again.

4. Select Next Node:

o Choose the unvisited node with the smallest tentative distance.

o Repeat steps 2–4 until all nodes are visited or the shortest path is found.

Example

Consider the following graph:

Code

(A)---4---(B)

| |

2 5

| |

(C)---1---(D)

• Start at A:

o Distance to A = 0

o Distance to B = 4

o Distance to C = 2

• Next, visit C (smallest distance = 2):

o Distance to D = 2 + 1 = 3

• Next, visit D:

o Distance to B = min(4, 3+5=8) → remains 4

• Final shortest paths:

o A→C→D=3

o A→B=4

Pseudocode

text

function Dijkstra(Graph, source):

dist[source] = 0
for each vertex v in Graph:

if v ≠ source:

dist[v] = ∞

create priority queue Q

[Link](source, dist[source])

while Q is not empty:

u = vertex in Q with smallest dist

remove u from Q

for each neighbor v of u:

alt = dist[u] + weight(u, v)

if alt < dist[v]:

dist[v] = alt

Q.add_or_update(v, alt)

return dist

Complexity

• Time Complexity:

o Using simple arrays: 𝑂(𝑉 2 )

o Using min-priority queue (heap): 𝑂((𝑉 + 𝐸) ⋅ log 𝑉)

• Space Complexity: 𝑂(𝑉 + 𝐸)

Applications

• GPS navigation (finding shortest driving routes)

• Network routing (like OSPF protocol)

• Robotics (path planning)

• Game AI (shortest pathfinding)

That’s the full detailed breakdown! You can now copy this into Word/Google Docs and export it
as a PDF.
Would you like me to also design a visual diagram of the algorithm’s flow (like a step-by-step chart)
so your PDF looks more polished?

Perfect, Rafe! You want examples of Dijkstra’s Algorithm in every programming language. Since
“every language” is infinite, I’ll give you a solid set of the most popular and widely used ones (C,
C++, Java, Python, JavaScript, and a couple extras like Go and Rust). You can copy these into your PDF
to make it comprehensive.

Dijkstra’s Algorithm – Code Examples in Multiple Languages

Python

python

import heapq

def dijkstra(graph, start):

dist = {node: float('inf') for node in graph}

dist[start] = 0

pq = [(0, start)]

while pq:

current_dist, u = [Link](pq)

if current_dist > dist[u]:

continue

for v, weight in graph[u]:

if dist[u] + weight < dist[v]:

dist[v] = dist[u] + weight

[Link](pq, (dist[v], v))

return dist

graph = {

'A': [('B', 4), ('C', 2)],

'B': [('A', 4), ('D', 5)],


'C': [('A', 2), ('D', 1)],

'D': [('B', 5), ('C', 1)]

print(dijkstra(graph, 'A'))

Java

java

import [Link].*;

class Dijkstra {

static class Edge {

int to, weight;

Edge(int t, int w) { to = t; weight = w; }

public static Map<Integer, Integer> dijkstra(Map<Integer, List<Edge>> graph, int start) {

Map<Integer, Integer> dist = new HashMap<>();

for (int node : [Link]()) [Link](node, Integer.MAX_VALUE);

[Link](start, 0);

PriorityQueue<int[]> pq = new PriorityQueue<>([Link](a -> a[0]));

[Link](new int[]{0, start});

while (![Link]()) {

int[] curr = [Link]();

int d = curr[0], u = curr[1];

if (d > [Link](u)) continue;

for (Edge e : [Link](u)) {


int newDist = [Link](u) + [Link];

if (newDist < [Link]([Link])) {

[Link]([Link], newDist);

[Link](new int[]{newDist, [Link]});

return dist;

C++

cpp

#include <bits/stdc++.h>

using namespace std;

vector<int> dijkstra(int n, vector<vector<pair<int,int>>> &graph, int start) {

vector<int> dist(n, INT_MAX);

dist[start] = 0;

priority_queue<pair<int,int>, vector<pair<int,int>>, greater<>> pq;

[Link]({0, start});

while (![Link]()) {

auto [d, u] = [Link](); [Link]();

if (d > dist[u]) continue;

for (auto [v, w] : graph[u]) {

if (dist[u] + w < dist[v]) {

dist[v] = dist[u] + w;
[Link]({dist[v], v});

return dist;

JavaScript ([Link])

javascript

function dijkstra(graph, start) {

const dist = {};

const pq = [[0, start]];

for (let node in graph) dist[node] = Infinity;

dist[start] = 0;

while ([Link]) {

[Link]((a, b) => a[0] - b[0]);

const [d, u] = [Link]();

if (d > dist[u]) continue;

for (let [v, w] of graph[u]) {

if (dist[u] + w < dist[v]) {

dist[v] = dist[u] + w;

[Link]([dist[v], v]);

return dist;

}
const graph = {

A: [["B", 4], ["C", 2]],

B: [["A", 4], ["D", 5]],

C: [["A", 2], ["D", 1]],

D: [["B", 5], ["C", 1]]

};

[Link](dijkstra(graph, "A"));

Rust

rust

use std::collections::{BinaryHeap, HashMap};

fn dijkstra(graph: &HashMap<&str, Vec<(&str, i32)>>, start: &str) -> HashMap<&str, i32> {

let mut dist: HashMap<&str, i32> = [Link]().map(|&k| (k, i32::MAX)).collect();

[Link](start, 0);

let mut heap = BinaryHeap::new();

[Link]((0, start));

while let Some((d, u)) = [Link]() {

if -d > dist[u] { continue; }

for &(v, w) in &graph[u] {

let new_dist = dist[u] + w;

if new_dist < dist[v] {

[Link](v, new_dist);

[Link]((-new_dist, v));

}
}

dist

Go

go

package main

import (

"container/heap"

"fmt"

type Edge struct{ to, weight int }

type Item struct{ dist, node int }

type PQ []Item

func (pq PQ) Len() int { return len(pq) }

func (pq PQ) Less(i, j int) bool { return pq[i].dist < pq[j].dist }

func (pq PQ) Swap(i, j int) { pq[i], pq[j] = pq[j], pq[i] }

func (pq *PQ) Push(x interface{}) { *pq = append(*pq, x.(Item)) }

func (pq *PQ) Pop() interface{} {

old := *pq

n := len(old)

item := old[n-1]

*pq = old[:n-1]

return item

}
func dijkstra(graph map[int][]Edge, start int) map[int]int {

dist := map[int]int{}

for node := range graph { dist[node] = 1<<31 - 1 }

dist[start] = 0

pq := &PQ{{0, start}}

[Link](pq)

for [Link]() > 0 {

item := [Link](pq).(Item)

if [Link] > dist[[Link]] { continue }

for _, e := range graph[[Link]] {

newDist := dist[[Link]] + [Link]

if newDist < dist[[Link]] {

dist[[Link]] = newDist

[Link](pq, Item{newDist, [Link]})

return dist

func main() {

graph := map[int][]Edge{

0: {{1, 4}, {2, 2}},

1: {{0, 4}, {3, 5}},

2: {{0, 2}, {3, 1}},


3: {{1, 5}, {2, 1}},

[Link](dijkstra(graph, 0))

With these examples, your PDF will look professional and complete.

Would you like me to also add a comparison table of syntax differences (Python vs C++ vs Java etc.)
so readers can quickly see how each language handles Dijkstra’s core logic?

You might also like