-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraph.java
More file actions
73 lines (56 loc) · 1.83 KB
/
Graph.java
File metadata and controls
73 lines (56 loc) · 1.83 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
/*import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
class Graph {
private int numVertices;
private List<List<Integer>> adjList;
public Graph(int numVertices) {
this.numVertices = numVertices;
adjList = new ArrayList<>(numVertices);
for (int i = 0; i < numVertices; i++) {
adjList.add(new ArrayList<>());
}
}
public void addEdge(int src, int dest) {
adjList.get(src).add(dest);
adjList.get(dest).add(src);
}
public void dfs(int startVertex) {
int[] colors = new int[numVertices];
for (int i = 0; i < numVertices; i++) {
colors[i] = -1;
}
dfsUtil(startVertex, colors);
}
private void dfsUtil(int vertex, int[] colors) {
colors[vertex] = 0;
System.out.println("Visiting vertex: " + vertex);
for (int neighbor : adjList.get(vertex)) {
if (colors[neighbor] == -1) {
dfsUtil(neighbor, colors);
}
}
}
public void bfs(int startVertex) {
int[] colors = new int[numVertices];
for (int i = 0; i < numVertices; i++) {
colors[i] = -1;
}
colors[startVertex] = 0;
Queue<Integer> queue = new LinkedList<>();
queue.offer(startVertex);
while (!queue.isEmpty()) {
int vertex = queue.poll();
System.out.println("Visiting vertex: " + vertex);
int nextColor = colors[vertex] + 1;
for (int neighbor : adjList.get(vertex)) {
if (colors[neighbor] == -1) {
colors[neighbor] = nextColor;
queue.offer(neighbor);
}
}
}
}
}
*/