diff options
author | Michael Hunteman <michael@michaelted.xyz> | 2022-09-22 10:14:04 -0500 |
---|---|---|
committer | Michael Hunteman <michael@michaelted.xyz> | 2022-09-22 10:14:04 -0500 |
commit | 6522012065712fb0ece31bff9ff10b38a83b10e1 (patch) | |
tree | 743f3c13d08be9f60bad57b74e7a1fe7cc675e89 /CloneGraph.java |
Initial commit
Diffstat (limited to 'CloneGraph.java')
-rw-r--r-- | CloneGraph.java | 39 |
1 files changed, 39 insertions, 0 deletions
diff --git a/CloneGraph.java b/CloneGraph.java new file mode 100644 index 0000000..ada085c --- /dev/null +++ b/CloneGraph.java @@ -0,0 +1,39 @@ +import java.lang.*; +import java.util.*; +import node.*; + +class CloneGraph { + public static GraphNode cloneGraph(GraphNode node) { + Stack<GraphNode> stack = new Stack<GraphNode>(); + ArrayList<GraphNode> visited = new ArrayList<GraphNode>(); + stack.push(node); + GraphNode clone = new GraphNode(node.val, node.neighbors); + while (!stack.empty()) { + node = stack.pop(); + if (visited.contains(node)) + continue; + GraphNode curr = new GraphNode(node.val, node.neighbors); + visited.add(node); + System.out.println("Node: " + node.val); + System.out.print("Neighbors: "); + for (GraphNode neighbor : node.neighbors) { + stack.push(neighbor); + System.out.print(neighbor.val + " "); + } + System.out.println(); + } + return clone; + } + + public static void main(String[] args) { + GraphNode head = new GraphNode(1); + GraphNode first = new GraphNode(2); + GraphNode second = new GraphNode(3); + GraphNode third = new GraphNode(4, new ArrayList<>(Arrays.asList(first, second))); + second.neighbors = new ArrayList<>(Arrays.asList(head, third)); + first.neighbors = new ArrayList<>(Arrays.asList(head, second)); + head.neighbors = new ArrayList<>(Arrays.asList(first, second)); + + GraphNode curr = cloneGraph(head); + } +} |