Skip to content

Commit d861991

Browse files
committed
update: added method to check if path exists between given two Vertex
1 parent 96c6950 commit d861991

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

β€ŽInterview Prep/section20_Graph/Graph.java

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,4 +96,28 @@ public void dispaly() {
9696
}
9797
System.out.println("--------------------------");
9898
}
99+
100+
public boolean hasPath(String vname1, String vname2, HashMap<String, Boolean> processed) {
101+
102+
processed.put(vname1, true);
103+
104+
// check direct edge
105+
if (this.containsEdge(vname1, vname2)) {
106+
return true;
107+
}
108+
109+
// check in neighbors
110+
Vertex vtx = vertices.get(vname1);
111+
112+
ArrayList<String> neighbors1 = new ArrayList<>(vtx.nbrs.keySet());
113+
114+
for (String nbrKey : neighbors1) {
115+
if (!processed.containsKey(nbrKey)) {
116+
if (hasPath(nbrKey, vname2, processed)) {
117+
return true;
118+
}
119+
}
120+
}
121+
return false;
122+
}
99123
}

0 commit comments

Comments
Β (0)