Skip to content

Commit 42ac51c

Browse files
committed
adding bidirectional search algorithm
1 parent 0984c81 commit 42ac51c

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

BreadthFirstSearchExample.java

+45
Original file line numberDiff line numberDiff line change
@@ -49,4 +49,49 @@ public static void Bfs(Node root)
4949
}
5050
}
5151
}
52+
53+
public static void Bfs(Node root, char destination)
54+
{
55+
Queue<Node> queue = new LinkedList<Node>();
56+
root.visited = true;
57+
queue.add(root);
58+
59+
while(!queue.isEmpty())
60+
{
61+
Node n = queue.remove();
62+
n.visited = true;
63+
64+
for(Node r : n.adjacent)
65+
{
66+
if(r.visited == false)
67+
{
68+
r.visited = true;
69+
r.parent = n;
70+
71+
if(r.key == destination)
72+
{
73+
// returns parent path to root
74+
String parentPath = calcParentPath(r);
75+
System.out.println(parentPath);
76+
}
77+
78+
queue.add(r);
79+
}
80+
}
81+
}
82+
83+
// couldn't find destination
84+
}
85+
86+
private static String calcParentPath(Node r)
87+
{
88+
Node p = r.parent;
89+
String path = r.key + " ";
90+
while(p != null)
91+
{
92+
path += p.key + " ";
93+
p = p.parent;
94+
}
95+
return path;
96+
}
5297
}

0 commit comments

Comments
 (0)