1#include<bits/stdc++.h>
2using namespace std;
3
4int main()
5{
6 int n = 9;
7
8 int mat[9][9] = { { 100,4,100,100,100,100,100,8,100},
9 { 4,100,8,100,100,100,100,11,100},
10 {100,8,100,7,100,4,100,100,2},
11 {100,100,7,100,9,14,100,100,100},
12 {100,100,100,9,100,100,100,100,100},
13 {100,100,4,14,10,100,2,100,100},
14 {100,100,100,100,100,2,100,1,6},
15 {8,11,100,100,100,100,1,100,7},
16 {100,100,2,100,100,100,6,7,100}};
17
18 int src = 0;
19 int count = 1;
20
21 int path[n];
22 for(int i=0;i<n;i++)
23 path[i] = mat[src][i];
24
25 int visited[n] = {0};
26 visited[src] = 1;
27
28 while(count<n)
29 {
30 int minNode;
31 int minVal = 100;
32
33 for(int i=0;i<n;i++)
34 if(visited[i] == 0 && path[i]<minVal)
35 {
36 minVal = path[i];
37 minNode = i;
38 }
39
40 visited[minNode] = 1;
41
42 for(int i=0;i<n;i++)
43 if(visited[i] == 0)
44 path[i] = min(path[i],minVal+mat[minNode][i]);
45
46 count++;
47 }
48
49 path[src] = 0;
50 for(int i=0;i<n;i++)
51 cout<<src<<" -> "<<path[i]<<endl;
52
53 return(0);
54}
1//Dijkstra's Algorithm (Using priority queue)
2//Watch Striver graph series on youtube I learned from there
3#include<bits/stdc++.h>
4using namespace std;
5void addedge(vector<pair<int,int>>adj[],int u,int v,int w)
6{
7 adj[u].push_back(make_pair(v,w));
8 adj[v].push_back(make_pair(u,w));
9}
10void Dijkstra(vector<pair<int,int>>adj[],int source,int n)
11{
12 priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>> prior; //Min-Heap storing will store distance and node
13 vector<int>dist(n,INT_MAX);
14 dist[source]=0;
15 prior.push(make_pair(0,source));
16 while(!prior.empty())
17 {
18 int distance=prior.top().first;
19 int node=prior.top().second;
20 prior.pop();
21 for(auto it:adj[node])
22 {
23 int next_node=it.first;
24 int next_weight=it.second;
25 if(dist[next_node]>distance+next_weight)
26 {
27 dist[next_node]=dist[node]+next_weight;
28 prior.push(make_pair(dist[next_node],next_node));
29 }
30 }
31 }
32 for(int i=0;i<n;i++)
33 {
34 cout<<dist[i]<<" ";
35 }
36}
37int main()
38{
39 int vertex,edges;
40 cout<<"ENTER THE NUMBER OF VERTEX AND EDGES:"<<endl;
41 cin>>vertex>>edges;
42 vector<pair<int,int>>adj[vertex];
43 int a,b,w;
44 cout<<"ENTER THE LINK AND THEN WEIGHT:"<<endl;
45 for(int i=0;i<edges;i++)
46 {
47 cin>>a>>b>>w;
48 addedge(adj,a,b,w);
49 }
50 int source;
51 cout<<"ENTER THE SOURCE NODE FROM WHICH YOU WANT TO CALCULATE THE SHORTEST DISTANCE:"<<endl;
52 cin>>source;
53 Dijkstra(adj,source,vertex);
54 return 0;
55}
56
1#include <limits.h>
2#include <stdio.h>
3
4
5#define V 9
6
7
8int minDistance(int dist[], bool sptSet[])
9{
10
11 int min = INT_MAX, min_index;
12
13 for (int v = 0; v < V; v++)
14 if (sptSet[v] == false && dist[v] <= min)
15 min = dist[v], min_index = v;
16
17 return min_index;
18}
19
20
21void printSolution(int dist[])
22{
23 printf("Vertex \t\t Distance from Source\n");
24 for (int i = 0; i < V; i++)
25 printf("%d \t\t %d\n", i, dist[i]);
26}
27
28
29void dijkstra(int graph[V][V], int src)
30{
31 int dist[V];
32
33
34 bool sptSet[V];
35
36 for (int i = 0; i < V; i++)
37 dist[i] = INT_MAX, sptSet[i] = false;
38
39
40 dist[src] = 0;
41
42
43 for (int count = 0; count < V - 1; count++) {
44
45 int u = minDistance(dist, sptSet);
46
47
48 sptSet[u] = true;
49
50
51 for (int v = 0; v < V; v++)
52
53
54 if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX
55 && dist[u] + graph[u][v] < dist[v])
56 dist[v] = dist[u] + graph[u][v];
57 }
58
59
60 printSolution(dist);
61}
62
63
64int main()
65{
66
67 int graph[V][V] = { { 0, 4, 0, 0, 0, 0, 0, 8, 0 },
68 { 4, 0, 8, 0, 0, 0, 0, 11, 0 },
69 { 0, 8, 0, 7, 0, 4, 0, 0, 2 },
70 { 0, 0, 7, 0, 9, 14, 0, 0, 0 },
71 { 0, 0, 0, 9, 0, 10, 0, 0, 0 },
72 { 0, 0, 4, 14, 10, 0, 2, 0, 0 },
73 { 0, 0, 0, 0, 0, 2, 0, 1, 6 },
74 { 8, 11, 0, 0, 0, 0, 1, 0, 7 },
75 { 0, 0, 2, 0, 0, 0, 6, 7, 0 } };
76
77 dijkstra(graph, 0);
78
79 return 0;
80}
1//djikstra's algorithm using a weighted graph (STL)
2//code by Soumyadepp
3//insta: @soumyadepp
4//linkedinID: https://www.linkedin.com/in/soumyadeep-ghosh-90a1951b6/
5
6#include <bits/stdc++.h>
7#define ll long long
8using namespace std;
9
10//to find the closest unvisited vertex from the source
11//note that numbering of vertices starts from 1 here. Calculate accordingly
12ll minDist(ll dist[], ll n, bool visited[])
13{
14 ll min = INT_MAX;
15 ll minIndex = 0;
16 for (ll i = 1; i <= n; i++)
17 {
18 if (!visited[i] && dist[i] <= min)
19 {
20 min = dist[i];
21 minIndex = i;
22 }
23 }
24 return minIndex;
25}
26
27//djikstra's algorithm for single source shortest path
28void djikstra(vector<pair<ll, ll>> *g, ll n, ll src)
29{
30 bool visited[n + 1];
31 ll dist[n + 1];
32 for (ll i = 0; i <= n; i++)
33 {
34 dist[i] = INT_MAX;
35 visited[i] = false;
36 }
37
38 dist[src] = 0;
39
40 for (ll i = 0; i < n - 1; i++)
41 {
42 ll u = minDist(dist, n, visited);
43 visited[u] = true;
44 for (ll v = 0; v < g[u].size(); v++)
45 {
46 if (dist[u] + g[u][v].second < dist[g[u][v].first])
47 {
48 dist[g[u][v].first] = dist[u] + g[u][v].second;
49 }
50 }
51 }
52 cout << "VERTEX : DISTANCE" << endl;
53 for (ll i = 1; i <= n; i++)
54 {
55 if (dist[i] != INT_MAX)
56 cout << i << " " << dist[i] << endl;
57 else
58 cout << i << " "
59 << "not reachable" << endl;
60 }
61 cout << endl;
62}
63
64int main()
65{
66 //to store the adjacency list which also contains the weight
67 vector<pair<ll, ll>> *graph;
68 ll n, e, x, y, w, src;
69 cout << "Enter number of vertices and edges in the graph" << endl;
70 cin >> n >> e;
71 graph = new vector<pair<ll, ll>>[n + 1];
72 cout << "Enter edges and weight" << endl;
73 for (ll i = 0; i < e; i++)
74 {
75 cin >> x >> y >> w;
76 //checking for invalid edges and negative weights.
77 if (x <= 0 || y <= 0 || w <= 0)
78 {
79 cout << "Invalid parameters. Exiting" << endl;
80 exit(-1);
81 }
82 graph[x].push_back(make_pair(y, w));
83 graph[y].push_back(make_pair(x, w));
84 }
85 cout << "Enter source from which you want to find shortest paths" << endl;
86 cin >> src;
87 if (src >= 1 && src <= n)
88 djikstra(graph, n, src);
89 else
90 cout << "Please enter a valid vertex as the source" << endl;
91 return 0;
92}
93
94//time complexity : O(ElogV)
95//space complexity: O(V)
96
1
2# Providing the graph
3n = int(input("Enter the number of vertices of the graph"))
4
5# using adjacency matrix representation
6vertices = [[0, 0, 1, 1, 0, 0, 0],
7 [0, 0, 1, 0, 0, 1, 0],
8 [1, 1, 0, 1, 1, 0, 0],
9 [1, 0, 1, 0, 0, 0, 1],
10 [0, 0, 1, 0, 0, 1, 0],
11 [0, 1, 0, 0, 1, 0, 1],
12 [0, 0, 0, 1, 0, 1, 0]]
13
14edges = [[0, 0, 1, 2, 0, 0, 0],
15 [0, 0, 2, 0, 0, 3, 0],
16 [1, 2, 0, 1, 3, 0, 0],
17 [2, 0, 1, 0, 0, 0, 1],
18 [0, 0, 3, 0, 0, 2, 0],
19 [0, 3, 0, 0, 2, 0, 1],
20 [0, 0, 0, 1, 0, 1, 0]]
21
22# Find which vertex is to be visited next
23def to_be_visited():
24 global visited_and_distance
25 v = -10
26 for index in range(num_of_vertices):
27 if visited_and_distance[index][0] == 0 \
28 and (v < 0 or visited_and_distance[index][1] <=
29 visited_and_distance[v][1]):
30 v = index
31 return v
32
33
34num_of_vertices = len(vertices[0])
35
36visited_and_distance = [[0, 0]]
37for i in range(num_of_vertices-1):
38 visited_and_distance.append([0, sys.maxsize])
39
40for vertex in range(num_of_vertices):
41
42 # Find next vertex to be visited
43 to_visit = to_be_visited()
44 for neighbor_index in range(num_of_vertices):
45
46 # Updating new distances
47 if vertices[to_visit][neighbor_index] == 1 and
48 visited_and_distance[neighbor_index][0] == 0:
49 new_distance = visited_and_distance[to_visit][1]
50 + edges[to_visit][neighbor_index]
51 if visited_and_distance[neighbor_index][1] > new_distance:
52 visited_and_distance[neighbor_index][1] = new_distance
53
54 visited_and_distance[to_visit][0] = 1
55
56i = 0
57
58# Printing the distance
59for distance in visited_and_distance:
60 print("Distance of ", chr(ord('a') + i),
61 " from source vertex: ", distance[1])
62 i = i + 1
1function Dijkstra(Graph, source):
2 dist[source] := 0 // Distance from source to source is set to 0
3 for each vertex v in Graph: // Initializations
4 if v ≠ source
5 dist[v] := infinity // Unknown distance function from source to each node set to infinity
6 add v to Q // All nodes initially in Q
7
8 while Q is not empty: // The main loop
9 v := vertex in Q with min dist[v] // In the first run-through, this vertex is the source node
10 remove v from Q
11
12 for each neighbor u of v: // where neighbor u has not yet been removed from Q.
13 alt := dist[v] + length(v, u)
14 if alt < dist[u]: // A shorter path to u has been found
15 dist[u] := alt // Update distance of u
16
17 return dist[]
18 end function
19