import java.util.ArrayList; public class Graph { ArrayList> adjList; public Graph() { adjList = new ArrayList<>(); } public void addNode(Node n) { adjList.add(n); } public static void main(String[] args) { Graph g = new Graph<>(); Node a = new Node('a'); Node b = new Node('b'); Node c = new Node('c'); Node d = new Node('d'); Node e = new Node('e'); g.addNode(a); g.addNode(b); g.addNode(c); g.addNode(d); g.addNode(e); a.addEdgeTo(b, "aa"); a.addEdgeTo(c, "bb"); a.addEdgeTo(d, "gg"); b.addEdgeTo(c, "cc"); b.addEdgeTo(a, "dd"); b.addEdgeTo(d, "ee"); c.addEdgeTo(e, "ff"); d.addEdgeTo(e, "hh"); System.out.println("Reachable from " + a); g.reachable(a); System.out.println("Reachable from " + a); g.reachableNoSelf(a); System.out.println("Reachable from " + b); g.reachable(b); System.out.println("Reachable from " + c); g.reachable(c); System.out.println("Path from A to E"); g.findPath1(a, e); System.out.println("Path from A to E"); g.findPath2(a, e); System.out.println("Done"); } public void reachable(Node n) { ArrayList> r = new ArrayList<>(); iReachable(n, r); for (Node nn : r) System.out.println(nn); } private void iReachable(Node n, ArrayList> rble) { if (rble.contains(n)) return; rble.add(n); for (Edge e : n.getEdges()) iReachable(e.getToo(), rble); } public void reachableNoSelf(Node n) { ArrayList> r = new ArrayList<>(); iReachableNoSelf(n, r); for (Node nn : r) System.out.println(nn); } private void iReachableNoSelf(Node n, ArrayList> rble) { for (Edge e : n.getEdges()) { if (!rble.contains(e.getToo())) { rble.add(e.getToo()); iReachableNoSelf(e.getToo(), rble); } } } public void findPath2(Nodefrom, Node too) { ArrayList> r = new ArrayList<>(); Node strt = new Node<>(from.getValue()); Edge ed = new Edge<>(strt, from, "QQQ"); ArrayList> edges = iFindPath2(ed, too, r); if (edges==null || edges.size()==0) System.out.println("No path"); else for (Edge e : edges) System.out.println(e); } private ArrayList> iFindPath2(Edge ee, Node dest, ArrayList> rble) { if (ee.getToo() == dest) { ArrayList> ret = new ArrayList<>(); return ret; } if (rble.contains(ee.getToo())) return null; Node n = ee.getToo(); for (Edge e : n.getEdges()) { ArrayList > rtn = iFindPath2(e, dest, rble); if (rtn!=null) { rtn.add(e); return rtn; } } return null; } public void findPath1(Nodefrom, Node too) { ArrayList> r = new ArrayList<>(); boolean b = iFindPath1(from, too, r); if (!b) System.out.println("No Path"); else System.out.println(from); } private boolean iFindPath1(Node current, Nodedest, ArrayList> rble) { if (current == dest) return true; if (rble.contains(current)) return false; rble.add(current); for (Edge e : current.getEdges()) { boolean b = iFindPath1(e.getToo(), dest, rble); if (b) { System.out.println(e.getToo()); return true; } } return false; } }