-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGraph.java
91 lines (85 loc) · 2.69 KB
/
Graph.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
83
84
85
86
87
88
89
90
91
import com.sun.org.apache.xpath.internal.operations.Bool;
import javax.print.attribute.HashPrintRequestAttributeSet;
import java.lang.Boolean;
import java.util.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
class Graph{
public class GraphNode{
int id = -1;
ArrayList<GraphNode> neighbors = new ArrayList<GraphNode>();
public GraphNode(int i){
id = i;
}
}
public GraphNode dfs(GraphNode root, HashMap<GraphNode,Boolean> map, int target){
if (root.id == target){
return root;
}else {
for (GraphNode node : root.neighbors){
if (!map.containsKey(node)){
map.put(node,true);
return dfs(node,map,target);
}
}
return null;
}
}
public GraphNode bfs(ArrayList<GraphNode> current,HashMap<GraphNode, Boolean> map, int target){
ArrayList<GraphNode> next = new ArrayList<GraphNode>();
for (GraphNode node : current){
if (node.id == target){
return node;
}else {
map.put(node,true);
for (GraphNode neighbor : node.neighbors){
if (!map.containsKey(neighbor)){
next.add(neighbor);
}
}
}
}
return bfs(next,map,target);
}
public GraphNode dfsI(GraphNode root, int target){
HashMap<GraphNode, Boolean> map = new HashMap<GraphNode, Boolean>();
Stack<GraphNode> st = new Stack<GraphNode>();
st.push(root);
while (!st.isEmpty()){
GraphNode ptr = st.pop();
map.put(ptr,true);
if (ptr.id == target){
return ptr;
}else {
for (GraphNode node : ptr.neighbors){
if (!map.containsKey(node)){
st.push(node);
}
}
}
}
return null;
}
public GraphNode bfsI(GraphNode root, int target){
HashMap<GraphNode,Boolean> map = new HashMap<GraphNode, Boolean>();
Queue<GraphNode> q = new LinkedList<GraphNode>();
q.add(root);
while (!q.isEmpty()){
GraphNode ptr = q.poll();
map.put(ptr,true);
if (ptr.id == target){
return ptr;
}else {
for (GraphNode node : ptr.neighbors){
if (!map.containsKey(node)){
q.add(node);
}
}
}
}
return null;
}
}