-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathGraph.java
More file actions
65 lines (56 loc) · 1.75 KB
/
Copy pathGraph.java
File metadata and controls
65 lines (56 loc) · 1.75 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
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
public class Graph {
public List<Edge> graph[];
public Graph(int n) {
graph = new LinkedList[n];
for (int i = 0; i < graph.length; i++){
graph[i] = new LinkedList<Edge>();
}
}
public void addEdge(int u, int v, int w){
// 0 to add at the beginning of linked list as complexity is less
graph[u].add(0, new Edge(v, w));
}
public boolean isConnected(int u, int v){
ListIterator<Edge> iterator = graph[u].listIterator();
while(iterator.hasNext()){
if(iterator.next().getV() == v)
return true;
}
return false;
}
public void DFS(int s){
boolean value[] = new boolean[graph.length];
DFSrec(s, value);
}
private void DFSrec(int v, boolean visited[]){
visited[v] = true;
System.out.println(v+" ");
ListIterator<Edge> iterator = graph[v].listIterator();
while(iterator.hasNext()){
Edge e = iterator.next();
if(!visited[e.getV()])
DFSrec(e.getV(), visited);
}
}
public void printList(){
for(int i = 0; i < graph.length; i++){
ListIterator<Edge> iterator = graph[i].listIterator();
while(iterator.hasNext()){
System.out.print(iterator.next()+" -> ");
}
System.out.print(" null");
System.out.println();
}
}
@Override
public String toString() {
String s = "";
for(int i=0; i<graph.length; i++){
s += i + " -> " + graph[i] + "\n";
}
return s;
}
}