-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathGraphAlgorithms.java
More file actions
243 lines (204 loc) · 6.91 KB
/
Copy pathGraphAlgorithms.java
File metadata and controls
243 lines (204 loc) · 6.91 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
package algorithms.graph;
import java.util.*;
/**
* Basic graph algorithms implementations.
*
* This class provides implementations of fundamental graph algorithms including:
* - Breadth-First Search (BFS)
* - Depth-First Search (DFS)
* - Cycle detection
* - Path finding
*/
public class GraphAlgorithms {
/**
* Simple graph representation using adjacency list.
*/
public static class Graph {
private int vertices;
private List<List<Integer>> adjList;
public Graph(int vertices) {
this.vertices = vertices;
this.adjList = new ArrayList<>(vertices);
for (int i = 0; i < vertices; i++) {
adjList.add(new ArrayList<>());
}
}
public void addEdge(int source, int dest) {
adjList.get(source).add(dest);
}
public void addUndirectedEdge(int source, int dest) {
adjList.get(source).add(dest);
adjList.get(dest).add(source);
}
public List<Integer> getNeighbors(int vertex) {
return adjList.get(vertex);
}
public int getVertices() {
return vertices;
}
}
/**
* Breadth-First Search (BFS) traversal.
*
* Time Complexity: O(V + E) where V is vertices and E is edges
* Space Complexity: O(V)
*
* @param graph the graph to traverse
* @param start starting vertex
* @return list of vertices in BFS order
*/
public static List<Integer> bfs(Graph graph, int start) {
List<Integer> result = new ArrayList<>();
boolean[] visited = new boolean[graph.getVertices()];
Queue<Integer> queue = new LinkedList<>();
visited[start] = true;
queue.offer(start);
while (!queue.isEmpty()) {
int vertex = queue.poll();
result.add(vertex);
for (int neighbor : graph.getNeighbors(vertex)) {
if (!visited[neighbor]) {
visited[neighbor] = true;
queue.offer(neighbor);
}
}
}
return result;
}
/**
* Depth-First Search (DFS) traversal.
*
* Time Complexity: O(V + E)
* Space Complexity: O(V)
*
* @param graph the graph to traverse
* @param start starting vertex
* @return list of vertices in DFS order
*/
public static List<Integer> dfs(Graph graph, int start) {
List<Integer> result = new ArrayList<>();
boolean[] visited = new boolean[graph.getVertices()];
dfsHelper(graph, start, visited, result);
return result;
}
private static void dfsHelper(Graph graph, int vertex, boolean[] visited, List<Integer> result) {
visited[vertex] = true;
result.add(vertex);
for (int neighbor : graph.getNeighbors(vertex)) {
if (!visited[neighbor]) {
dfsHelper(graph, neighbor, visited, result);
}
}
}
/**
* Check if the graph has a cycle (for directed graphs).
*
* Time Complexity: O(V + E)
* Space Complexity: O(V)
*
* @param graph the graph to check
* @return true if graph has a cycle, false otherwise
*/
public static boolean hasCycle(Graph graph) {
boolean[] visited = new boolean[graph.getVertices()];
boolean[] recStack = new boolean[graph.getVertices()];
for (int i = 0; i < graph.getVertices(); i++) {
if (hasCycleHelper(graph, i, visited, recStack)) {
return true;
}
}
return false;
}
private static boolean hasCycleHelper(Graph graph, int vertex, boolean[] visited, boolean[] recStack) {
if (recStack[vertex]) {
return true; // Cycle detected
}
if (visited[vertex]) {
return false;
}
visited[vertex] = true;
recStack[vertex] = true;
for (int neighbor : graph.getNeighbors(vertex)) {
if (hasCycleHelper(graph, neighbor, visited, recStack)) {
return true;
}
}
recStack[vertex] = false;
return false;
}
/**
* Find shortest path between two vertices (BFS-based for unweighted graphs).
*
* Time Complexity: O(V + E)
* Space Complexity: O(V)
*
* @param graph the graph
* @param start start vertex
* @param end end vertex
* @return list representing the shortest path, or empty list if no path exists
*/
public static List<Integer> findShortestPath(Graph graph, int start, int end) {
if (start == end) {
return Arrays.asList(start);
}
boolean[] visited = new boolean[graph.getVertices()];
int[] parent = new int[graph.getVertices()];
Arrays.fill(parent, -1);
Queue<Integer> queue = new LinkedList<>();
visited[start] = true;
queue.offer(start);
while (!queue.isEmpty()) {
int vertex = queue.poll();
for (int neighbor : graph.getNeighbors(vertex)) {
if (!visited[neighbor]) {
visited[neighbor] = true;
parent[neighbor] = vertex;
queue.offer(neighbor);
if (neighbor == end) {
return reconstructPath(parent, start, end);
}
}
}
}
return new ArrayList<>(); // No path found
}
private static List<Integer> reconstructPath(int[] parent, int start, int end) {
List<Integer> path = new ArrayList<>();
for (int vertex = end; vertex != -1; vertex = parent[vertex]) {
path.add(vertex);
}
Collections.reverse(path);
return path;
}
/**
* Example usage and testing.
*/
public static void main(String[] args) {
System.out.println("=== Graph Algorithms Demo ===\n");
// Create a sample graph
// 0 → 1 → 2
// ↓ ↓ ↓
// 3 → 4 5
Graph graph = new Graph(6);
graph.addEdge(0, 1);
graph.addEdge(0, 3);
graph.addEdge(1, 2);
graph.addEdge(1, 4);
graph.addEdge(2, 5);
graph.addEdge(3, 4);
System.out.println("BFS starting from vertex 0:");
System.out.println(bfs(graph, 0));
System.out.println("\nDFS starting from vertex 0:");
System.out.println(dfs(graph, 0));
System.out.println("\nShortest path from 0 to 5:");
System.out.println(findShortestPath(graph, 0, 5));
System.out.println("\nHas cycle: " + hasCycle(graph));
// Create a graph with a cycle
Graph cyclicGraph = new Graph(4);
cyclicGraph.addEdge(0, 1);
cyclicGraph.addEdge(1, 2);
cyclicGraph.addEdge(2, 3);
cyclicGraph.addEdge(3, 1); // Creates a cycle
System.out.println("\nCyclic graph has cycle: " + hasCycle(cyclicGraph));
}
}