Skip to content

Commit 41e37d0

Browse files
committed
update: added Depth First Search (DFS) implementation
1 parent 9fe3937 commit 41e37d0

File tree

1 file changed

+64
-2
lines changed

1 file changed

+64
-2
lines changed

β€ŽInterview Prep/section20_Graph/Graph.java

Lines changed: 64 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,7 @@ public boolean bfs(String src, String dest) {
154154
if (processed.containsKey(removePair.vname)) {
155155
continue;
156156
}
157-
157+
158158
processed.put(removePair.vname, true);
159159

160160
// check direct edge
@@ -165,7 +165,7 @@ public boolean bfs(String src, String dest) {
165165

166166
// devote work to neighbors
167167

168-
Vertex removePairVertex = this.vertices.get(removePair.vname);
168+
Vertex removePairVertex = this.vertices.get(removePair.vname); // address
169169
// all neighbors of removedPair vertex
170170
ArrayList<String> removePairNbrs = new ArrayList<>(removePairVertex.nbrs.keySet());
171171

@@ -188,4 +188,66 @@ public boolean bfs(String src, String dest) {
188188
return false;
189189
}
190190

191+
// Depth First Search implementation
192+
// it first explores all neighbors & then only it's siblings
193+
194+
public boolean dfs(String src, String dest) {
195+
196+
HashMap<String, Boolean> processed = new HashMap<>();
197+
198+
// use addLast() and removeFirst() of LinkedList - O(1) Time operations
199+
LinkedList<Pair> stack = new LinkedList<>(); // Queue using LinkedList
200+
201+
// create a new Pair
202+
Pair srcPair = new Pair();
203+
srcPair.vname = src;
204+
srcPair.pathSoFar = src;
205+
206+
// put the new pair in queue
207+
stack.addFirst(srcPair);
208+
209+
// while queue is not empty keep on doing the work
210+
while (!stack.isEmpty()) {
211+
212+
// remove a pair from the queue
213+
Pair removePair = stack.removeFirst();
214+
215+
// check if that vertex is already processed
216+
if (processed.containsKey(removePair.vname)) {
217+
continue;
218+
}
219+
220+
processed.put(removePair.vname, true);
221+
222+
// check direct edge
223+
if (this.containsEdge(removePair.vname, dest)) {
224+
System.out.println(removePair.pathSoFar + dest);
225+
return true;
226+
}
227+
228+
// devote work to neighbors
229+
230+
Vertex removePairVertex = this.vertices.get(removePair.vname); // address
231+
// all neighbors of removedPair vertex
232+
ArrayList<String> removePairNbrs = new ArrayList<>(removePairVertex.nbrs.keySet());
233+
234+
// loop on neighbors
235+
for (String nbr : removePairNbrs) {
236+
237+
// process only unprocessed neighbors
238+
if (!processed.containsKey(nbr)) {
239+
240+
// make a new pair of neighbor & put it in Queue
241+
Pair newPair = new Pair();
242+
newPair.vname = nbr;
243+
newPair.pathSoFar = removePair.pathSoFar + nbr;
244+
245+
stack.addFirst(newPair);
246+
}
247+
}
248+
}
249+
250+
return false;
251+
}
252+
191253
}

0 commit comments

Comments
Β (0)