Skip to content

Commit cb81a2c

Browse files
authored
Add files via upload
1 parent 6a527e8 commit cb81a2c

9 files changed

+701
-0
lines changed
+68
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
public struct Edge
2+
{
3+
public int Source;
4+
public int Destination;
5+
public int Weight;
6+
}
7+
8+
public struct Graph
9+
{
10+
public int VerticesCount;
11+
public int EdgesCount;
12+
public Edge[] edge;
13+
}
14+
15+
public static Graph CreateGraph(int verticesCount, int edgesCount)
16+
{
17+
Graph graph = new Graph();
18+
graph.VerticesCount = verticesCount;
19+
graph.EdgesCount = edgesCount;
20+
graph.edge = new Edge[graph.EdgesCount];
21+
22+
return graph;
23+
}
24+
25+
private static void Print(int[] distance, int count)
26+
{
27+
Console.WriteLine("Vertex Distance from source");
28+
29+
for (int i = 0; i < count; ++i)
30+
Console.WriteLine("{0}\t {1}", i, distance[i]);
31+
}
32+
33+
public static void BellmanFord(Graph graph, int source)
34+
{
35+
int verticesCount = graph.VerticesCount;
36+
int edgesCount = graph.EdgesCount;
37+
int[] distance = new int[verticesCount];
38+
39+
for (int i = 0; i < verticesCount; i++)
40+
distance[i] = int.MaxValue;
41+
42+
distance[source] = 0;
43+
44+
for (int i = 1; i <= verticesCount - 1; ++i)
45+
{
46+
for (int j = 0; j < edgesCount; ++j)
47+
{
48+
int u = graph.edge[j].Source;
49+
int v = graph.edge[j].Destination;
50+
int weight = graph.edge[j].Weight;
51+
52+
if (distance[u] != int.MaxValue && distance[u] + weight < distance[v])
53+
distance[v] = distance[u] + weight;
54+
}
55+
}
56+
57+
for (int i = 0; i < edgesCount; ++i)
58+
{
59+
int u = graph.edge[i].Source;
60+
int v = graph.edge[i].Destination;
61+
int weight = graph.edge[i].Weight;
62+
63+
if (distance[u] != int.MaxValue && distance[u] + weight < distance[v])
64+
Console.WriteLine("Graph contains negative weight cycle.");
65+
}
66+
67+
Print(distance, verticesCount);
68+
}
+81
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
package ShortestPath;
2+
3+
import java.util.*;
4+
5+
class Edge {
6+
int source;
7+
int dest;
8+
int weight;
9+
10+
public Edge(int source, int dest, int weight) {
11+
this.source = source;
12+
this.dest = dest;
13+
this.weight = weight;
14+
}
15+
}
16+
17+
public class BellmanFords {
18+
19+
public static void printPath(int parent[], int v) {
20+
if (v < 0) return;
21+
22+
printPath(parent, parent[v]);
23+
System.out.print(v + " ");
24+
}
25+
26+
public static void BellmanFord(List<Edge> edges, int source, int N) {
27+
int E = edges.size();
28+
29+
int distance[] = new int[N];
30+
int parent[] = new int[N];
31+
32+
Arrays.fill(distance, Integer.MAX_VALUE);
33+
distance[source] = 0;
34+
35+
Arrays.fill(parent, -1);
36+
int K = N;
37+
while (--K > 0) {
38+
for(int j=0; j<E; j++) {
39+
int u = edges.get(j).source;
40+
int v = edges.get(j).dest;
41+
int w = edges.get(j).weight;
42+
43+
if (distance[u] != Integer.MAX_VALUE && (distance[u]+w) < distance[v]) {
44+
distance[v] = distance[u] + w;
45+
parent[v] = u;
46+
}
47+
}
48+
}
49+
50+
/// Check for negative weight cycles
51+
for(int i=0; i<E; i++) {
52+
int u = edges.get(i).source;
53+
int v = edges.get(i).dest;
54+
int w = edges.get(i).weight;
55+
56+
if (distance[u] != Integer.MAX_VALUE && (distance[u]+w) < distance[v]) {
57+
System.out.println("Negative weight cycle Found!!");
58+
}
59+
}
60+
61+
for (int i=0; i<N; i++) {
62+
System.out.print("Distance of vertex " + i + " from the source is " + distance[i] + ". It's path is [ ");
63+
printPath(parent, i);
64+
System.out.println("]");
65+
}
66+
67+
}
68+
69+
public static void main(String[] args) {
70+
List<Edge> edges = Arrays.asList(
71+
new Edge(0, 1,-1), new Edge(0, 2, 4),
72+
new Edge(1, 2, 3), new Edge(1, 3, 2),
73+
new Edge(1, 4, 2), new Edge(3, 2, 5),
74+
new Edge(3, 1, 1), new Edge(4, 3,-3)
75+
);
76+
int source = 0;
77+
int N = 5;
78+
79+
BellmanFord(edges, source, N);
80+
}
81+
}
+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
from sys import maxint
2+
class BellmanFord( object ):
3+
4+
def __init__( self ):
5+
'''
6+
Constructor
7+
'''
8+
9+
def singleSourceShortestPath( self, weight, source ) :
10+
# auxiliary constants
11+
SIZE = len( weight )
12+
EVE = -1; # to indicate no predecessor
13+
INFINITY = maxint
14+
15+
# declare and initialize pred to EVE and minDist to INFINITY
16+
pred = [EVE] * SIZE
17+
minDist = [INFINITY] * SIZE
18+
19+
# set minDist[source] = 0 because source is 0 distance from itself.
20+
minDist[source] = 0
21+
22+
# relax the edge set V-1 times to find all shortest paths
23+
for i in range( 1, SIZE - 1 ):
24+
for v in range( SIZE ):
25+
for x in self.adjacency( weight, v ):
26+
if minDist[x] > minDist[v] + weight[v][x]:
27+
minDist[x] = minDist[v] + weight[v][x]
28+
pred[x] = v
29+
30+
# detect cycles if any
31+
for v in range( SIZE ):
32+
for x in self.adjacency( weight, v ):
33+
if minDist[x] > minDist[v] + weight[v][x]:
34+
raise Exception( "Negative cycle found" )
35+
36+
return [pred, minDist]
37+
38+
39+
#=====================================================================
40+
# Retrieve all the neighbors of vertex v.
41+
#=====================================================================
42+
def adjacency( self, G, v ) :
43+
result = []
44+
for x in range( len( G ) ):
45+
if G[v][x] is not None:
46+
result.append( x )
47+
48+
return result;

Algorithms/ShortestPath/Dijkstras.cpp

+112
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
/**
2+
Pseudo Code for Dijkstra’s Algorithm:
3+
------------------------------------
4+
5+
function Dijkstra(Graph, source):
6+
dist[source] := 0 // Distance from source to source
7+
for each vertex v in Graph: // Initializations
8+
if v ≠ source
9+
dist[v] := infinity // Unknown distance function from source to v
10+
previous[v] := undefined // Previous node in optimal path from source
11+
end if
12+
add v to Q // All nodes initially in Q
13+
end for
14+
15+
while Q is not empty: // The main loop
16+
u := vertex in Q with min dist[u] // Source node in first case
17+
remove u from Q
18+
19+
for each neighbor v of u: // where v has not yet been removed from Q.
20+
alt := dist[u] + length(u, v)
21+
if alt < dist[v]: // A shorter path to v has been found
22+
dist[v] := alt
23+
previous[v] := u
24+
end if
25+
end for
26+
end while
27+
return dist[], previous[]
28+
end function
29+
30+
**/
31+
32+
#include<bits/stdc++.h>
33+
using namespace std;
34+
35+
#define INF 9999
36+
#define MAX 10
37+
38+
void dijikstra(int G[MAX][MAX], int n, int startnode);
39+
40+
int main()
41+
{
42+
int G[MAX][MAX], i, j, n, u;
43+
printf("\nEnter the no. of vertices:: ");
44+
scanf("%d", &n);
45+
46+
printf("\nEnter the adjacency matrix::\n");
47+
for(i=0;i < n;i++)
48+
for(j=0;j < n;j++)
49+
scanf("%d", &G[i][j]);
50+
51+
printf("\nEnter the starting node:: ");
52+
scanf("%d", &u);
53+
54+
dijikstra(G,n,u);
55+
56+
return 0;
57+
}
58+
59+
void dijikstra(int G[MAX][MAX], int n, int startnode) {
60+
int cost[MAX][MAX], distance[MAX], pred[MAX];
61+
int visited[MAX], count, mindistance, nextnode, i,j;
62+
63+
for(i=0; i<n; i++)
64+
for(j=0; j<n; j++)
65+
if(G[i][j]==0)
66+
cost[i][j]=INF;
67+
else
68+
cost[i][j]=G[i][j];
69+
70+
for(i=0; i<n; i++) {
71+
distance[i]=cost[startnode][i];
72+
pred[i]=startnode;
73+
visited[i]=0;
74+
}
75+
76+
distance[startnode]=0;
77+
visited[startnode]=1;
78+
count=1;
79+
while(count < n-1) {
80+
mindistance=INF;
81+
for(i=0; i<n; i++) {
82+
if(distance[i] < mindistance&&!visited[i]) {
83+
mindistance=distance[i];
84+
nextnode=i;
85+
}
86+
}
87+
88+
visited[nextnode]=1;
89+
for(i=0; i<n; i++) {
90+
if(!visited[i]) {
91+
if(mindistance+cost[nextnode][i] < distance[i]) {
92+
distance[i]=mindistance+cost[nextnode][i];
93+
pred[i]=nextnode;
94+
}
95+
}
96+
}
97+
count++;
98+
}
99+
100+
for(i=0; i<n; i++) {
101+
if(i!=startnode) {
102+
printf("\nDistance of %d = %d", i, distance[i]);
103+
printf("\nPath = %d", i);
104+
j=i;
105+
do {
106+
j=pred[j];
107+
printf(" <-%d", j);
108+
}
109+
while(j!=startnode);
110+
}
111+
}
112+
}

Algorithms/ShortestPath/Dijkstras.cs

+50
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
private static int MinimumDistance(int[] distance, bool[] shortestPathTreeSet, int verticesCount)
2+
{
3+
int min = int.MaxValue;
4+
int minIndex = 0;
5+
6+
for (int v = 0; v < verticesCount; ++v)
7+
{
8+
if (shortestPathTreeSet[v] == false && distance[v] <= min)
9+
{
10+
min = distance[v];
11+
minIndex = v;
12+
}
13+
}
14+
15+
return minIndex;
16+
}
17+
18+
private static void Print(int[] distance, int verticesCount)
19+
{
20+
Console.WriteLine("Vertex Distance from source");
21+
22+
for (int i = 0; i < verticesCount; ++i)
23+
Console.WriteLine("{0}\t {1}", i, distance[i]);
24+
}
25+
26+
public static void Dijkstra(int[,] graph, int source, int verticesCount)
27+
{
28+
int[] distance = new int[verticesCount];
29+
bool[] shortestPathTreeSet = new bool[verticesCount];
30+
31+
for (int i = 0; i < verticesCount; ++i)
32+
{
33+
distance[i] = int.MaxValue;
34+
shortestPathTreeSet[i] = false;
35+
}
36+
37+
distance[source] = 0;
38+
39+
for (int count = 0; count < verticesCount - 1; ++count)
40+
{
41+
int u = MinimumDistance(distance, shortestPathTreeSet, verticesCount);
42+
shortestPathTreeSet[u] = true;
43+
44+
for (int v = 0; v < verticesCount; ++v)
45+
if (!shortestPathTreeSet[v] && Convert.ToBoolean(graph[u, v]) && distance[u] != int.MaxValue && distance[u] + graph[u, v] < distance[v])
46+
distance[v] = distance[u] + graph[u, v];
47+
}
48+
49+
Print(distance, verticesCount);
50+
}

0 commit comments

Comments
 (0)