Skip to content

Commit

Permalink
Add GraphSearch API with DFS algorithm.
Browse files Browse the repository at this point in the history
  • Loading branch information
theViz343 committed Nov 3, 2023
1 parent a74906c commit 9fd0504
Showing 1 changed file with 53 additions and 9 deletions.
62 changes: 53 additions & 9 deletions src/main/java/GraphData.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.List;

public class GraphData {
Graph<String, DefaultEdge> graphObject = new DefaultDirectedGraph<>(DefaultEdge.class);
Expand Down Expand Up @@ -124,6 +125,47 @@ public boolean addEdge(String srcLabel, String dstLabel) {
}
}

public Path GraphSearch(String src, String dst) {
Path p = new Path();
String source = src;
HashMap<String, Boolean> visited = new HashMap<>();
HashMap<String, String> parent = new HashMap<>();

Stack<String> stack = new Stack<>();
visited.put(src, true);
stack.push(src);

while (!stack.isEmpty()) {

src = stack.pop();
if (Objects.equals(src, dst)) {
break;
}
List<String> successors = Graphs.neighborListOf(graphObject,src);
for (String node : successors) {

if (visited.get(node)==null) {
visited.put(node, true);
parent.put(node,src);
stack.push(node);
}
}
}
String node = dst;
p.add(node);
if (visited.get(dst) != null) {
while (true) {
if (Objects.equals(node, source)) {
return p;
}
node = parent.get(node);
p.add(node);
}
} else {
return null;
}
}

public void removeEdge(String srcLabel, String dstLabel) throws Exception {
DefaultEdge edgeexisting = graphObject.getEdge(srcLabel, dstLabel);
if (edgeexisting==null) {
Expand Down Expand Up @@ -167,15 +209,17 @@ public static void main(String[] args) {
GraphData graphApi = new GraphData();
graphApi.parseGraph("src/main/resources/example.dot");
System.out.println(graphApi.toString());
graphApi.outputGraph("src/main/resources/output.txt");
graphApi.addNodes(new String[]{"Z", "X"});
System.out.println(graphApi.toString());
graphApi.addEdge("Z", "X");
System.out.println(graphApi.toString());
graphApi.addEdge("Z", "X");
System.out.println(graphApi.toString());
graphApi.outputDOTGraph("src/main/resources/gen_graph.dot");
graphApi.outputGraphics("src/main/resources/", "png");
Path path = graphApi.GraphSearch("C","D");
path.printPath();
// graphApi.outputGraph("src/main/resources/output.txt");
// graphApi.addNodes(new String[]{"Z", "X"});
// System.out.println(graphApi.toString());
// graphApi.addEdge("Z", "X");
// System.out.println(graphApi.toString());
// graphApi.addEdge("Z", "X");
// System.out.println(graphApi.toString());
// graphApi.outputDOTGraph("src/main/resources/gen_graph.dot");
// graphApi.outputGraphics("src/main/resources/", "png");



Expand Down

0 comments on commit 9fd0504

Please sign in to comment.