Dijkstra's Algorithm in C
Dijkstra's Algorithm in C
#include <iostream>
#include <limits.h>
#include <float.h>
using namespace std;
#define MAXNODOS 500 maximum size of the network
#define UNDEFINED -1
int N;
float dist[MAXNODOS][MAXNODOS];
float minimum[MAXNODES];
int anterior[MAXNODOS];
bool visited[MAXNODES];
bool minimumUnvisitedNode (int * node)
{
int candidate = -1;
for (int n = 0; n < N; n++) {
if (!visited[n] && (minimo[n] < minimum[candidate] ||
candidate == -1)) {
candidate = n;
}
}
*node = candidate;
return candidate != -1;
}
void dijkstra (int origin, int destination) {
minimo[origen] = 0.0;
int node;
while (unvisitedNodeMin(&node)) {
if (minimum[node] == FLT_MAX)
return; others
vertices are inaccessible
visited[node] = true;
for (int n = 0; n < N; n++) {
if (!visited[n] && distance[node][n] < 1.0) {
float possibleMin = minimum[node] +
distance[node][n];
if (possibleMin < minimum[n]) {
minimo[n] = possibleMin;
previous[n] = node;
}}}}}
void shortest_path (int start, int end)
{
if (start != end) {
minimum_path (start, previous[final]);
,
}
cout << final;
}
int main(int argc, char **argv)
{
int
// initialize distance matrix and shortest path
cin >> N;
for (int k = 0; k < N; k++) {
anterior[k] = UNDEFINED;
false
minimo[k] = MAXINT;
for (int l = 0; l < N; l++) {
path[k][l] = FLT_MAX;
}
}
read distances in real arcs
cin >> M;
for (int k = 0; k < M; k++) {
int i, j;
cin >> i >> j;
cin >> prob[i][j];
}
cin >> start >> end;
dijkstra(start, end);
minimum_path(start, end);
return 0;
}
IN PSEUDOCODE
Dijkstra function (Graph G, source_node s)
We will use a vector to store the distances from the exit node to the rest.
int distance[n] //We initialize the vector with initial distances
boolean seen[n] //boolean vector to control the vertices of the
that we already have the minimum distance
for each w ∈ V[G] do
If (there is no edge between s and w) then
Infinity //you can mark the box with a -1 for
example
Serial number
weight(s, w)
end if
end for
distancia[s] = 0
seen
//n is the number of vertices that the Graph has
while (not_seen_all) do
vertex = take_the_minimum_of_the_distance_vector that has not been seen;
view[vertex] = true;
for each w ∈ successors (G, vertex) do
if distance[w] > distance[vertex] + weight(vertex, w) then
distance[w] = distance[vertex] + weight(vertex, w)
finally yes
end for
end while
end function
Floyd's Algorithm
Start
Build the adjacency matrix F, keeping in mind that F(i,j)=0 if i = j
(main diagonal is 0). Also, where there is no path, it must be indicated with
infinite.
For k from 1 to n
For i from 1 to n
For j from 1 to n
F[i,j]=min(F[i,j], F[i,k] + F[k,j])
End for j
End for i
End for k
In the k-th lap, F[i, j] will contain the value of the shortest path that a
to vertex i with j such that the path does not pass through a vertex with number
greater than k.
The resulting matrix is that of the minimum paths between each node. If you
wants to know what that path is, a customized tree must be built taking
as node number to k every time an optimization is detected.
#include <fstream.h>
#include <iostream.h>
#include <conio.h>
#define INF 999
#define N 3
void display(int [N][N]);
void main()
{
int k,i,j;
int F[N][N]={ 0, 8, 5, 3, 0, INF, INF, 2, 0 };
clear screen();
k = 0
show(F);
for(k=0;k<N;k++)
{
for(i=0;i<N;i++)
{
for(j=0;j<N;j++)
{
if(i!=j){
cout << "Fk [" << (i+1) << ", " << (j+1) << "] = min(Fk-1[";
cout << (i+1) << ", " << (j+1) << "], Fk-1[";
print << (i+1) << ", " << (k+1) << "] + Fk-1[
cout << (k+1) << ", " << (j+1) << "])" << endl;
cout << " " << F[i][j];
cout << " " << F[i][k] + F[k][j];
if(F[i][j] > F[i][k] + F[k][j])
{
F[i][j] = F[i][k] + F[k][j];
=>Fk [
cout << (j+1) << "] = " << F[i][j]; }
cout << endl;}}}
k =
show(F);
}
void show(int F[N][N])
{
int i,j;
for(i=0;i<N;i++)
{
for(j=0;j<N;j++)
{
cout << F[i][j] << "\t";
}
cout << endl;}}
WARSHALL ALGORITHM
Start
W(i,j)=0 if i = j (the main diagonal is 0).
For k from 1 to n
For i from 1 to n
For j from 1 to n
IF (i!=j) W[i,j]=W[i,j] OR W[i,k] AND W[k,j]
End for j
End for i
End for k
The resulting matrix indicates whether a path is possible regardless of its
length.
The expression of the inner cycle states that there exists a path i->j such that NOT
passes through the vertex with a number greater than k if:
There is already a path i->j that does not pass through a path with a "number" greater than k-1.
Ó
There is a path i -> k that does not go through the vertex with the "number" greater than
k-1 and if there is a path k->j that does not pass through a vertex with a higher number
what k-1
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
class path
{
int n;
int p[10][10];
int a[10][10];
int c[10][10];
public
void get();
void pm();
void ap();
void disp();
};
void path::get()
int i,j,k;
clrscr();
cout << "Enter the number of nodes in the graph:";
cin >> n;
Enter the adjacency matrix :
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{// cout << "a[" << i << "," << j << "] = ";
cin >> a[i][j];
p[i][j]=0;
}}
cout<<"Enter The cost matrix is :";
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{// cout << "a[" << i << "," << j << "] = ";
cin >> c[i][j];
}}
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{p[i][j]=a[i][j];
}}}
void path::disp()
{
The output matrix for the given graph is:
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
cout << p[i][j] << ";
void path::pm()
int i,j,k;
for(k=1;k<=n;k++)
{
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
p[i][j] = p[i][j] || (p[i][k] && p[k][j]);
}}}}
void path::ap()
{
int i,j,k;
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
p[i][j]=c[i][j];
}}
for(k=1;k<=n;k++)
{
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++){
if(p[i][j] < p[i][k] + p[k][j])
{p[i][j]=p[i][j];}
else{
p[i][j]=p[i][k]+p[k][j];}}}}}
void main()
{
path p;
p.get();
p.pm();
cout << "path matrix is :";
p.display();
getch();
p.ap();
cout << "all pair shortest path matrix is :";
p.disp();
getch();}
PRIM'S ALGORITHM
JARNIK (Graph G, source_node s)
We initialize all the nodes of the graph. We set the distance to infinity.
and the parent of each node to NULL
We enqueue, in a priority queue where the priority is the distance,
all pairs <node,distance> of the graph
for each u in V[G] do
infinity
father[u] = NULL
Add(queue, <u, distance[u]>)
distancia[s]=0
while queue != 0 do
// NOTE: A node with higher priority is understood to be that which
distance[u] is smaller.
u = extract_min(cola) //returns the minimum and removes it from the
cola
for each v adjacent to 'u' do
if ((v ∈ queue) && (distance[v] > weight(u, v)) then
u
distance[v] = weight(u, v)
Update(queue,<v,distance[v]>)
KRUSKAL'S ALGORITHM
function Kruskal(G)
for each vertex v in G do
Define an elementary cluster C(v) ← {v}.
Initialize a priority queue Q to contain all edges in G, using the
weights as keys.
Define a tree T ← Ø // T will ultimately contain the edges of the
MST
// n is the total number of vertices
while T has fewer than n-1 edges
edge u, v is the minimum weighted route from/to v
remove minimum from Q
prevents cycles in T. add u, v only if T does not contain an edge
that a u and v.
Note that the cluster contains more than one vertex if an edge connects
a pair of
vertices that have been added to the tree.
Let C(v) be the cluster containing v, and let C(u) be the cluster
containingu.
if If C(v) ≠ C(u) then
Add edge (v,u) to T.
Merge C(v) and C(u) into one cluster, that is, union C(v) and C(u).
return treeT
#include<iostream>
#include<vector>
#include<algorithm>
#define max 100
using namespace std;
struct Edge{
int vi,vj,w;
};
bool lequal(Edge const* t1, Edge const* t2){
return (t1->w<t2->w);
int V, E;
vector <Edge*>edges;
vector <Edge*> mst;
int cicles[max];
int main(){
int i,W,number,c;
Edge *e;
c=1;
while(true){
edges.clear();
mst.clear();
cin >> V >> E;
if (!V && !E) break;
for(i=0;i<E;i++){
e = new Edge;
cin >> e->vi >> e->vj >> e->w;
edges.push_back(e);
}
Sort the edges from the beginning to the end using lequal.
for(i=0;i<V;i++) cicles[i] = i;
while(mst.size() < (V - 1) && edges.size()) {
if(cicles[edges[0]->vi]!=cicles[edges[0]->vj]){
cicles[edges[0]->vj];
for(i=0;i<V;i++) {
if(cicles[i]==number)
cicles[i] = cicles[edges[0]->vi];
mst.push_back(edges[0]);
edges.erase(edges.begin(), edges.begin() + 1);
W = 0;
for(i=0;i<mst.size();i++) {
W += mst[i]->w;
}
cout << "Case " << c++ << ":" << endl;
The Minimum Spanning Tree has cost:
}
return 0;
}