-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdjistra-alg.cpp
More file actions
93 lines (75 loc) · 2.35 KB
/
djistra-alg.cpp
File metadata and controls
93 lines (75 loc) · 2.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include <iostream>
using namespace std;
class Graph {
int **adjMatrix;
int vertices;
public:
Graph(int v) {
vertices = v;
adjMatrix = new int*[vertices];
for (int i = 0; i < vertices; i++) {
adjMatrix[i] = new int[vertices];
for (int j = 0; j < vertices; j++) {
adjMatrix[i][j] = (i == j) ? 0 : 1e9; // Large value for no direct edge
}
}
}
void addEdge(int u, int v, int w) {
adjMatrix[u][v] = w;
adjMatrix[v][u] = w; // Remove this line for directed graphs
}
void dijkstra(int start) {
int *dist = new int[vertices];
int *visited = new int[vertices];
for (int i = 0; i < vertices; i++) {
dist[i] = 1e9; // Initialize distances to a large value
visited[i] = 0;
}
dist[start] = 0;
for (int count = 0; count < vertices - 1; count++) {
int minDist = 1e9, minIndex = -1;
for (int v = 0; v < vertices; v++) {
if (!visited[v] && dist[v] < minDist) {
minDist = dist[v];
minIndex = v;
}
}
visited[minIndex] = 1;
for (int v = 0; v < vertices; v++) {
if (!visited[v] && adjMatrix[minIndex][v] != 1e9 &&
dist[minIndex] + adjMatrix[minIndex][v] < dist[v]) {
dist[v] = dist[minIndex] + adjMatrix[minIndex][v];
}
}
}
cout << "Shortest distances from node " << start << ":\n";
for (int i = 0; i < vertices; i++) {
cout << "To " << i << " -> " << (dist[i] == 1e9 ? -1 : dist[i]) << endl;
}
delete[] dist;
delete[] visited;
}
~Graph() {
for (int i = 0; i < vertices; i++) {
delete[] adjMatrix[i];
}
delete[] adjMatrix;
}
};
int main() {
int vertices, edges, u, v, w, start;
cout << "Enter number of vertices: ";
cin >> vertices;
Graph g(vertices);
cout << "Enter number of edges: ";
cin >> edges;
cout << "Enter edges (u v w):" << endl;
for (int i = 0; i < edges; i++) {
cin >> u >> v >> w;
g.addEdge(u, v, w);
}
cout << "Enter starting node for Dijkstra's Algorithm: ";
cin >> start;
g.dijkstra(start);
return 0;
}