-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.java
More file actions
405 lines (348 loc) · 13 KB
/
Copy pathMain.java
File metadata and controls
405 lines (348 loc) · 13 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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
import java.util.*;
/**
* Graph implementation using adjacency matrix representation.
* Supports weighted directed graphs with various algorithms for pathfinding and analysis.
*/
class Graph {
private static final int INFINITY = Integer.MAX_VALUE;
private final int[][] adjacencyMatrix;
private final int vertexCount;
/**
* Creates a new graph with the specified number of vertices.
*
* @param vertexCount the number of vertices in the graph
*/
public Graph(int vertexCount) {
this.vertexCount = vertexCount;
this.adjacencyMatrix = new int[vertexCount][vertexCount];
initializeMatrix();
}
private void initializeMatrix() {
for (int i = 0; i < vertexCount; i++) {
Arrays.fill(adjacencyMatrix[i], INFINITY);
}
}
/**
* Adds a weighted directed edge to the graph.
*
* @param source the source vertex
* @param destination the destination vertex
* @param weight the edge weight
*/
public void addEdge(int source, int destination, int weight) {
validateVertex(source);
validateVertex(destination);
adjacencyMatrix[source][destination] = weight;
}
/**
* Prints the adjacency matrix representation of the graph.
*/
public void printAdjacencyMatrix() {
System.out.println("Adjacency Matrix:");
for (int i = 0; i < vertexCount; i++) {
for (int j = 0; j < vertexCount; j++) {
if (adjacencyMatrix[i][j] == INFINITY) {
System.out.print("∞\t");
} else {
System.out.print(adjacencyMatrix[i][j] + "\t");
}
}
System.out.println();
}
}
private void validateVertex(int vertex) {
if (vertex < 0 || vertex >= vertexCount) {
throw new IllegalArgumentException("Vertex " + vertex + " is out of bounds");
}
}
/**
* Finds the shortest paths from a source vertex using the Bellman-Ford algorithm.
* Detects negative cycles if present.
*
* @param source the source vertex
*/
public void findShortestPathsBellmanFord(int source) {
validateVertex(source);
int[] distances = initializeDistances(source);
relaxEdges(distances);
if (hasNegativeCycle(distances)) {
System.out.println("The graph contains a negative cycle.");
return;
}
printShortestPaths(source, distances);
}
private int[] initializeDistances(int source) {
int[] distances = new int[vertexCount];
Arrays.fill(distances, INFINITY);
distances[source] = 0;
return distances;
}
private void relaxEdges(int[] distances) {
for (int k = 0; k < vertexCount - 1; k++) {
for (int i = 0; i < vertexCount; i++) {
for (int j = 0; j < vertexCount; j++) {
if (canRelaxEdge(i, j, distances)) {
distances[j] = distances[i] + adjacencyMatrix[i][j];
}
}
}
}
}
private boolean canRelaxEdge(int from, int to, int[] distances) {
return adjacencyMatrix[from][to] != INFINITY
&& distances[from] != INFINITY
&& distances[from] + adjacencyMatrix[from][to] < distances[to];
}
private boolean hasNegativeCycle(int[] distances) {
for (int i = 0; i < vertexCount; i++) {
for (int j = 0; j < vertexCount; j++) {
if (canRelaxEdge(i, j, distances)) {
return true;
}
}
}
return false;
}
private void printShortestPaths(int source, int[] distances) {
System.out.println("Shortest paths from vertex " + (source + 1) + ":");
for (int i = 0; i < vertexCount; i++) {
if (distances[i] == INFINITY) {
System.out.println("No path from vertex " + (source + 1) + " to vertex " + (i + 1));
} else {
System.out.println("Distance to vertex " + (i + 1) + ": " + distances[i]);
}
}
}
/**
* Finds all cycles in the graph using Depth-First Search (DFS).
*
* @return a list of cycles, where each cycle is represented as a list of vertices
*/
public List<List<Integer>> findCycles() {
List<List<Integer>> cycles = new ArrayList<>();
boolean[] visited = new boolean[vertexCount];
for (int i = 0; i < vertexCount; i++) {
if (!visited[i]) {
List<Integer> currentPath = new ArrayList<>();
dfsFindCycles(i, visited, new boolean[vertexCount], currentPath, cycles);
}
}
return cycles;
}
private void dfsFindCycles(int vertex, boolean[] visited, boolean[] inPath,
List<Integer> currentPath, List<List<Integer>> cycles) {
visited[vertex] = true;
inPath[vertex] = true;
currentPath.add(vertex);
for (int i = 0; i < vertexCount; i++) {
if (adjacencyMatrix[vertex][i] != INFINITY) {
if (inPath[i]) {
cycles.add(extractCycle(currentPath, i));
} else if (!visited[i]) {
dfsFindCycles(i, visited, inPath, currentPath, cycles);
}
}
}
inPath[vertex] = false;
currentPath.remove(currentPath.size() - 1);
}
private List<Integer> extractCycle(List<Integer> path, int cycleStart) {
List<Integer> cycle = new ArrayList<>();
int startIndex = path.indexOf(cycleStart);
for (int j = startIndex; j < path.size(); j++) {
cycle.add(path.get(j));
}
return cycle;
}
/**
* Calculates the height of the tree structure from a given node.
*
* @param node the starting node
* @return the height of the tree from the given node
*/
public int calculateHeight(int node) {
validateVertex(node);
boolean[] visited = new boolean[vertexCount];
return calculateHeightRecursive(node, visited);
}
private int calculateHeightRecursive(int node, boolean[] visited) {
visited[node] = true;
int maxHeight = 0;
for (int i = 0; i < vertexCount; i++) {
if (adjacencyMatrix[node][i] != INFINITY && !visited[i]) {
maxHeight = Math.max(maxHeight, calculateHeightRecursive(i, visited));
}
}
return maxHeight + 1;
}
/**
* Performs a pre-order traversal of the graph starting from a given node.
*
* @param node the starting node
*/
public void preOrderTraversal(int node) {
validateVertex(node);
boolean[] visited = new boolean[vertexCount];
System.out.print("Pre-order traversal from node " + (node + 1) + ": ");
preOrderTraversalRecursive(node, visited);
System.out.println();
}
private void preOrderTraversalRecursive(int node, boolean[] visited) {
visited[node] = true;
System.out.print((node + 1) + " ");
for (int i = 0; i < vertexCount; i++) {
if (adjacencyMatrix[node][i] != INFINITY && !visited[i]) {
preOrderTraversalRecursive(i, visited);
}
}
}
/**
* Finds the shortest path between two vertices using Dijkstra's algorithm.
*
* @param source the source vertex
* @param destination the destination vertex
*/
public void findShortestPathDijkstra(int source, int destination) {
validateVertex(source);
validateVertex(destination);
DijkstraResult result = runDijkstra(source);
printDijkstraPath(source, destination, result);
}
private DijkstraResult runDijkstra(int source) {
int[] distances = new int[vertexCount];
boolean[] visited = new boolean[vertexCount];
int[] predecessors = new int[vertexCount];
Arrays.fill(distances, INFINITY);
Arrays.fill(predecessors, -1);
distances[source] = 0;
PriorityQueue<Integer> queue = new PriorityQueue<>(Comparator.comparingInt(v -> distances[v]));
queue.add(source);
while (!queue.isEmpty()) {
int current = queue.poll();
if (visited[current]) continue;
visited[current] = true;
relaxAdjacentEdges(current, distances, visited, predecessors, queue);
}
return new DijkstraResult(distances, predecessors);
}
private void relaxAdjacentEdges(int current, int[] distances, boolean[] visited,
int[] predecessors, PriorityQueue<Integer> queue) {
for (int neighbor = 0; neighbor < vertexCount; neighbor++) {
if (adjacencyMatrix[current][neighbor] != INFINITY && !visited[neighbor]) {
int newDistance = distances[current] + adjacencyMatrix[current][neighbor];
if (newDistance < distances[neighbor]) {
distances[neighbor] = newDistance;
predecessors[neighbor] = current;
queue.add(neighbor);
}
}
}
}
private void printDijkstraPath(int source, int destination, DijkstraResult result) {
if (result.distances[destination] == INFINITY) {
System.out.println("No path from vertex " + (source + 1) + " to vertex " + (destination + 1));
} else {
System.out.println("Shortest path (Dijkstra) from vertex " + (source + 1) + " to vertex " + (destination + 1) + ":");
List<Integer> path = reconstructPath(destination, result.predecessors);
printPath(path);
System.out.println("\nTotal distance: " + result.distances[destination]);
}
}
private List<Integer> reconstructPath(int destination, int[] predecessors) {
List<Integer> path = new ArrayList<>();
for (int v = destination; v != -1; v = predecessors[v]) {
path.add(v);
}
Collections.reverse(path);
return path;
}
private void printPath(List<Integer> path) {
for (int i = 0; i < path.size(); i++) {
System.out.print((path.get(i) + 1));
if (i < path.size() - 1) {
System.out.print(" -> ");
}
}
}
private static class DijkstraResult {
final int[] distances;
final int[] predecessors;
DijkstraResult(int[] distances, int[] predecessors) {
this.distances = distances;
this.predecessors = predecessors;
}
}
}
/**
* Main class demonstrating graph operations and algorithms.
*/
public class Main {
public static void main(String[] args) {
Graph graph = createSampleGraph();
demonstrateGraphOperations(graph);
}
private static Graph createSampleGraph() {
Graph graph = new Graph(13);
addEdges(graph);
return graph;
}
private static void addEdges(Graph graph) {
graph.addEdge(0, 1, 200);
graph.addEdge(0, 12, 250);
graph.addEdge(0, 8, 290);
graph.addEdge(1, 5, 360);
graph.addEdge(1, 2, 190);
graph.addEdge(2, 5, 250);
graph.addEdge(2, 4, 190);
graph.addEdge(2, 0, 300);
graph.addEdge(3, 2, 180);
graph.addEdge(4, 5, 300);
graph.addEdge(4, 9, 400);
graph.addEdge(5, 10, 350);
graph.addEdge(5, 11, 300);
graph.addEdge(6, 3, 300);
graph.addEdge(6, 2, 250);
graph.addEdge(6, 0, 150);
graph.addEdge(7, 6, 200);
graph.addEdge(7, 0, 220);
graph.addEdge(8, 7, 180);
graph.addEdge(8, 12, 180);
graph.addEdge(9, 3, 200);
graph.addEdge(10, 9, 700);
graph.addEdge(10, 4, 200);
graph.addEdge(11, 1, 150);
graph.addEdge(12, 11, 100);
graph.addEdge(12, 1, 200);
}
private static void demonstrateGraphOperations(Graph graph) {
graph.printAdjacencyMatrix();
System.out.println();
graph.findShortestPathsBellmanFord(0);
System.out.println();
demonstrateCycleDetection(graph);
int height = graph.calculateHeight(0);
System.out.println("Tree height from vertex 1: " + height);
System.out.println();
graph.preOrderTraversal(0);
System.out.println();
graph.findShortestPathDijkstra(0, 2);
System.out.println();
}
private static void demonstrateCycleDetection(Graph graph) {
List<List<Integer>> cycles = graph.findCycles();
System.out.println("Cycles found:");
for (List<Integer> cycle : cycles) {
printCycle(cycle);
}
System.out.println();
}
private static void printCycle(List<Integer> cycle) {
for (int i = 0; i < cycle.size(); i++) {
System.out.print((cycle.get(i) + 1));
if (i < cycle.size() - 1) {
System.out.print(" -> ");
}
}
System.out.println();
}
}