-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDijkstraUser.java
More file actions
224 lines (182 loc) · 7.99 KB
/
Copy pathDijkstraUser.java
File metadata and controls
224 lines (182 loc) · 7.99 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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
import java.util.*;
public class DijkstraUser {
// Simple class to represent a connection between two nodes
static class Connection {
char from, to;
int weight;
Connection(char from, char to, int weight) {
this.from = from;
this.to = to;
this.weight = weight;
}
}
public static void main(String[] args) {
// Step 1: Define your graph connections
Connection[] connections = {
new Connection('A','C',3), new Connection('G','B',1), new Connection('F','H',12),
new Connection('C','F',9), new Connection('E','G',15), new Connection('G','I',10),
new Connection('A','D',5), new Connection('B','E',3), new Connection('I','E',5),
new Connection('C','D',2), new Connection('A','B',9), new Connection('F','G',4),
new Connection('G','D',6), new Connection('H','I',6)
};
// Step 2: Get available nodes and take user input
char[] availableNodes = getAllNodes(connections);
Scanner scanner = new Scanner(System.in);
System.out.println("=== DIJKSTRA'S SHORTEST PATH FINDER ===");
System.out.print("Available nodes: ");
for (int i = 0; i < availableNodes.length; i++) {
System.out.print(availableNodes[i]);
if (i < availableNodes.length - 1) System.out.print(", ");
}
System.out.println();
char startNode;
while (true) {
System.out.print("Enter starting node (from above): ");
String input = scanner.nextLine().trim().toUpperCase();
if (input.length() == 1) {
startNode = input.charAt(0);
// Check if the node exists in the graph
boolean nodeExists = false;
for (char node : availableNodes) {
if (node == startNode) {
nodeExists = true;
break;
}
}
if (nodeExists) {
break;
} else {
System.out.println("Error: Node '" + startNode + "' does not exist in the graph!");
}
} else {
System.out.println("Error: Please enter a single character!");
}
}
System.out.println("\nRunning Dijkstra's algorithm from node: " + startNode);
// Step 3: Run Dijkstra
dijkstra(connections, startNode);
scanner.close();
}
public static void dijkstra(Connection[] connections, char start) {
// Step 1: Find all unique nodes and store them in an array
char[] allNodes = getAllNodes(connections);
int numNodes = allNodes.length;
// Step 2: Initialize arrays for distances, previous nodes, and visited status
int[] distance = new int[numNodes];
char[] previous = new char[numNodes];
boolean[] visited = new boolean[numNodes];
// Set all distances to infinity, except start node
for (int i = 0; i < numNodes; i++) {
distance[i] = Integer.MAX_VALUE;
previous[i] = '-';
visited[i] = false;
}
// Set start node distance to 0
int startIndex = getNodeIndex(allNodes, start);
distance[startIndex] = 0;
// Step 3: Main algorithm loop
for (int count = 0; count < numNodes; count++) {
// Find the unvisited node with smallest distance
int currentIndex = findClosestNode(distance, visited, numNodes);
if (currentIndex == -1) break; // No more reachable nodes
visited[currentIndex] = true;
char current = allNodes[currentIndex];
// Check all neighbors of current node
for (Connection conn : connections) {
char neighbor = 0;
// Find if this connection involves current node
if (conn.from == current) {
neighbor = conn.to;
} else if (conn.to == current) {
neighbor = conn.from;
} else {
continue; // This connection doesn't involve current node
}
int neighborIndex = getNodeIndex(allNodes, neighbor);
// Skip if neighbor already visited
if (visited[neighborIndex]) continue;
// Calculate new distance through current node
int newDistance = distance[currentIndex] + conn.weight;
// If we found a shorter path, update it
if (newDistance < distance[neighborIndex]) {
distance[neighborIndex] = newDistance;
previous[neighborIndex] = current;
}
}
}
// Step 4: Print results
printResults(allNodes, distance, previous, start);
}
// Helper method: Get all unique nodes from connections
private static char[] getAllNodes(Connection[] connections) {
Set<Character> nodeSet = new HashSet<>();
for (Connection conn : connections) {
nodeSet.add(conn.from);
nodeSet.add(conn.to);
}
// Convert to array and sort for consistent ordering
char[] nodes = new char[nodeSet.size()];
int i = 0;
for (char node : nodeSet) {
nodes[i++] = node;
}
Arrays.sort(nodes);
return nodes;
}
// Helper method: Find the index of a node in the array
private static int getNodeIndex(char[] nodes, char target) {
for (int i = 0; i < nodes.length; i++) {
if (nodes[i] == target) {
return i;
}
}
return -1; // Not found
}
// Helper method: Find the unvisited node with minimum distance
private static int findClosestNode(int[] distance, boolean[] visited, int numNodes) {
int minDistance = Integer.MAX_VALUE;
int closestIndex = -1;
for (int i = 0; i < numNodes; i++) {
if (!visited[i] && distance[i] < minDistance) {
minDistance = distance[i];
closestIndex = i;
}
}
return closestIndex;
}
// Helper method: Print the path from start to target
private static void printPath(char[] allNodes, char[] previous, char target, char start) {
if (target == start) {
System.out.print(target);
return;
}
int targetIndex = getNodeIndex(allNodes, target);
char prev = previous[targetIndex];
if (prev == '-') {
System.out.print("-");
return;
}
printPath(allNodes, previous, prev, start);
System.out.print(" -> " + target);
}
// Helper method: Print all results in a nice format
private static void printResults(char[] allNodes, int[] distance, char[] previous, char start) {
System.out.println("\n=== DIJKSTRA'S ALGORITHM RESULTS ===");
System.out.println("Starting from node: " + start);
System.out.println("\nNode\tDistance\tPrevious\tPath from " + start);
System.out.println("----\t--------\t--------\t---------");
for (int i = 0; i < allNodes.length; i++) {
char node = allNodes[i];
int dist = distance[i];
char prev = previous[i];
System.out.printf("%c\t", node);
if (dist == Integer.MAX_VALUE) {
System.out.printf("∞\t\t-\t\tNo path\n");
} else {
System.out.printf("%d\t\t%c\t\t", dist, prev);
printPath(allNodes, previous, node, start);
System.out.println();
}
}
}
}