From 6abd8dff3a838681dd0b1d91c75a22f8d5ebd880 Mon Sep 17 00:00:00 2001 From: Squizard <184549450+BradyLeg@users.noreply.github.com> Date: Tue, 20 May 2025 11:43:33 -0700 Subject: [PATCH] Added methods --- src/Traverse.java | 54 ++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 49 insertions(+), 5 deletions(-) diff --git a/src/Traverse.java b/src/Traverse.java index 7945513..fc2b1f3 100644 --- a/src/Traverse.java +++ b/src/Traverse.java @@ -7,8 +7,8 @@ public class Traverse { public static void main(String[] args) { // See below site for visualization of this graph // https://auberonedu.github.io/graph-explore/graph_site/viz.html - Vertex v3 = new Vertex<>(3); - Vertex v7 = new Vertex<>(7); + Vertex v3 = new Vertex<>(3); + Vertex v7 = new Vertex<>(7); Vertex v12 = new Vertex<>(12); Vertex v34 = new Vertex<>(34); Vertex v56 = new Vertex<>(56); @@ -18,16 +18,60 @@ public static void main(String[] args) { Vertex v23 = new Vertex<>(23); Vertex v67 = new Vertex<>(67); - v3.neighbors = new ArrayList<>(List.of(v7, v34)); - v7.neighbors = new ArrayList<>(List.of(v12, v45, v34, v56)); + v3.neighbors = new ArrayList<>(List.of(v7, v34)); + v7.neighbors = new ArrayList<>(List.of(v12, v45, v34, v56)); v12.neighbors = new ArrayList<>(List.of(v7, v56, v78)); - v34.neighbors = new ArrayList<>(List.of(v34, v91)); + v34.neighbors = new ArrayList<>(List.of(v34, v91)); v56.neighbors = new ArrayList<>(List.of(v78)); v78.neighbors = new ArrayList<>(List.of(v91)); v91.neighbors = new ArrayList<>(List.of(v56)); v45.neighbors = new ArrayList<>(List.of(v23)); v23.neighbors = new ArrayList<>(List.of()); v67.neighbors = new ArrayList<>(List.of(v91)); + + System.out.println(); + // Set> myVisited = new HashSet<>(); + // traverse(v3); + int result = sum(v3); + System.out.println(result); + } + + public static int sum(Vertex current) { + Set> visited = new HashSet<>(); + return sum(current, visited); } + public static int sum(Vertex current, Set> visited) { + if (current == null || visited.contains(current)) + return 0; + + visited.add(current); + int total = 0; + total += current.data; + + for (Vertex neighbor : current.neighbors) { + int neighborSum = sum(neighbor, visited); + total += neighborSum; + } + + return total; + } + + public static void traverse(Vertex current) { + Set> myVisited = new HashSet<>(); + traverse(current, myVisited); + } + + public static void traverse(Vertex current, Set> visited) { + if (current == null || visited.contains(current)) { + return; + } + + System.out.println(current.data); + visited.add(current); + + for (Vertex neighbor : current.neighbors) { + traverse(neighbor, visited); + } + } }