-
Notifications
You must be signed in to change notification settings - Fork 0
/
GraphAL.java
100 lines (83 loc) · 2.29 KB
/
GraphAL.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
92
93
94
95
96
97
98
99
100
package com.keshav.ctci.trees;
import com.keshav.ctci.queue.Queue;
import java.util.ArrayList;
import java.util.List;
public class GraphAL {
public List<NodeAL> nodes;
public GraphAL() {
nodes = new ArrayList<>();
}
public void init(NodeAL node) {
if (node.visited())
return;
nodes.add(node);
node.markVisited();
for (NodeAL n : node.getChildren()) {
init(n);
}
}
public void insert(NodeAL n) {
nodes.add(n);
}
/*
* Search if path exists.
* */
public boolean search(NodeAL start, NodeAL end) {
if (start == end) return true;
resetVisited();
// Need to do BFS and stop at found node. Keep updating visited.
Queue<NodeAL> q = new Queue();
q.insert(start);
while (!q.isEmpty()) {
NodeAL node = q.deque();
if (!node.visited()) {
if (node == end)
return true;
node.markVisited();
for (NodeAL n : node.getChildren()) {
q.insert(n);
}
}
}
return false;
}
public void resetVisited() {
for (NodeAL n : nodes) {
n.resetVisited();
}
}
public String printNodes() {
String ret = "[";
for (NodeAL n : nodes) {
ret += n.getVal() + ", ";
}
ret += "]";
return ret;
}
@Override
public String toString() {
return "GraphAL{" +
"nodes=" + printNodes() +
'}';
}
public static void main(String args[]) {
NodeAL node = new NodeAL(5);
node.insert(new NodeAL(23));
NodeAL node1 = new NodeAL(50);
NodeAL node2 = new NodeAL(15);
node2.insert(new NodeAL(67));
node2.insert(new NodeAL(46));
node1.insert(node2);
node1.insert(new NodeAL(-1));
node1.insert(new NodeAL(3));
node1.insert(new NodeAL(10));
node.insert(node1);
NodeAL end = new NodeAL(42);
System.out.println(node);
GraphAL g = new GraphAL();
g.init(node);
g.insert(end);
System.out.println(g);
System.out.println(g.search(node, node2));
}
}