-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGraphs.java
82 lines (82 loc) · 2.66 KB
/
Graphs.java
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
// "static void main" must be defined in a public class.
public class Main {
public static void main(String[] args) {
int v = 5;
ArrayList<ArrayList<Integer>> adj = new ArrayList<>();
for(int i = 0; i<v; i++) {
adj.add(new ArrayList<Integer>());
}
/*
0 -> 1, 2
1 -> 0, 1, 2, 3
2 -> 0, 1
3 -> 1
*/
addEdge(adj, 0, 1);
addEdge(adj, 0, 2);
addEdge(adj, 1, 2);
addEdge(adj, 1, 3);
BFS(adj, 0);
shortestPath(adj, 0);
boolean[] visited = new boolean[adj.size()];
DFS(adj, 0, visited);
}
static void addEdge(ArrayList<ArrayList<Integer>> arr, int u, int v) {
arr.get(u).add(v);
arr.get(v).add(u);
}
static void BFS(ArrayList<ArrayList<Integer>> adj, int source) {
boolean visited[] = new boolean[adj.size()-1];
Queue<Integer> q = new LinkedList<>();
q.add(source);
visited[source] = true;
while(!q.isEmpty()) {
int curr = q.poll();
System.out.println(curr);
for(int vertex:adj.get(curr)) {
if(visited[vertex] == false) {
visited[vertex] = true;
q.offer(vertex);
}
}
}
}
static void shortestPath(ArrayList<ArrayList<Integer>> adj, int source) {
boolean visited[] = new boolean[adj.size()-1];
int[] distance = new int[adj.size()-1];
Queue<Integer> q = new LinkedList<>();
q.add(source);
//visited[source] = true;
distance[source] = 0;
while(!q.isEmpty()) {
int curr = q.poll();
for(int vertex:adj.get(curr)) {
if(visited[vertex] == false) {
distance[vertex] = distance[curr]+1;
visited[vertex] = true;
q.add(vertex);
}
}
}
System.out.println(Arrays.toString(distance));
}
static void DFS(ArrayList<ArrayList<Integer>>adj, int source, boolean[] visited) {
System.out.println(source);
visited[source] = true;
for(int vertex:adj.get(source)) {
if(visited[vertex] == false) {
visited[vertex] = true;
DFS(adj, vertex, visited);
}
}
}
//For disconnected graphs, run BFS on for each source.
/*static void bfsHelper(ArrayList<ArrayList<Integer>> adj, int source) {
boolean visited[] = new int[adj.size()];
for(int i = 0; i<adj.size(); i++) {
if(visited[i] == false) {
BFS(adj, i, visited);
}
}
}*/
}