diff --git a/src/main/java/GraphData.java b/src/main/java/GraphData.java index 4192395..c75cd89 100644 --- a/src/main/java/GraphData.java +++ b/src/main/java/GraphData.java @@ -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 graphObject = new DefaultDirectedGraph<>(DefaultEdge.class); @@ -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 visited = new HashMap<>(); + HashMap parent = new HashMap<>(); + + Stack stack = new Stack<>(); + visited.put(src, true); + stack.push(src); + + while (!stack.isEmpty()) { + + src = stack.pop(); + if (Objects.equals(src, dst)) { + break; + } + List 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) { @@ -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");