diff --git a/src/Traverse.java b/src/Traverse.java index 7945513..c3633be 100644 --- a/src/Traverse.java +++ b/src/Traverse.java @@ -28,6 +28,59 @@ public static void main(String[] args) { v45.neighbors = new ArrayList<>(List.of(v23)); v23.neighbors = new ArrayList<>(List.of()); v67.neighbors = new ArrayList<>(List.of(v91)); + // "List of" is immutable, but ArrayList is mutable - this is important! + + // Vertex v1 = new Vertex<>(1); + // System.out.println(v1.neighbors); + + dfs(v7); + System.out.println(); + dfs(v34); + + Vertex hello = new Vertex<>("Hello"); + Vertex world = new Vertex<>("world"); + Vertex exclaim = new Vertex<>("!"); + Vertex comma = new Vertex<>(","); + Vertex how = new Vertex<>("how"); + Vertex are = new Vertex<>("are"); + Vertex you = new Vertex<>("you"); + Vertex the = new Vertex<>("the"); + Vertex cats = new Vertex<>("cats"); + Vertex question = new Vertex<>("?"); + + hello.neighbors = new ArrayList<>(List.of(comma, world, how)); + world.neighbors = new ArrayList<>(List.of(exclaim)); + exclaim.neighbors = new ArrayList<>(List.of(hello)); + comma.neighbors = new ArrayList<>(List.of(world, how)); + how.neighbors = new ArrayList<>(List.of(are)); + are.neighbors = new ArrayList<>(List.of(you, the)); + you.neighbors = new ArrayList<>(List.of(question)); + the.neighbors = new ArrayList<>(List.of(cats)); + cats.neighbors = new ArrayList<>(List.of(question)); + question.neighbors = new ArrayList<>(List.of(question)); + + // dfs(comma); + + } + + // node = vertex = node - they are the same thing! + public static void dfs(Vertex vertex) { + dfs(vertex, new HashSet>()); + } + + private static void dfs(Vertex vertex, Set> visited) { + if (vertex == null) return; + if (visited.contains(vertex)) return; + + visited.add(vertex); + System.out.println(vertex.data); + + if (vertex.neighbors == null) return; + + for (var neighbor: vertex.neighbors) { + dfs(neighbor, visited); + } + } } diff --git a/src/Vertex.java b/src/Vertex.java index c48a92e..f685cdb 100644 --- a/src/Vertex.java +++ b/src/Vertex.java @@ -4,8 +4,10 @@ public class Vertex { T data; List> neighbors; + // List> neighbors = new ArrayList<>(); public Vertex(T data) { + // "this" calls "Vertex(data, new ArrayList<>)" this(data, new ArrayList<>()); }