File tree 1 file changed +45
-0
lines changed
1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change @@ -49,4 +49,49 @@ public static void Bfs(Node root)
49
49
}
50
50
}
51
51
}
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
+ }
52
97
}
You can’t perform that action at this time.
0 commit comments