📑 문제
https://leetcode.com/problems/clone-graph/
📑 문제 접근 방법
이문제는 graph문제이기 때문에, DFS 알고리즘을 이용하여 해결했습니다.
📑 CODE
/*
// Definition for a Node.
class Node {
public int val;
public List<Node> neighbors;
public Node() {
val = 0;
neighbors = new ArrayList<Node>();
}
public Node(int _val) {
val = _val;
neighbors = new ArrayList<Node>();
}
public Node(int _val, ArrayList<Node> _neighbors) {
val = _val;
neighbors = _neighbors;
}
}
*/
class Solution {
HashMap<Integer, Node> visited = new HashMap<>();
public Node cloneGraph(Node node) {
if (node == null) return null;
if (visited.containsKey(node.val)) return visited.get(node.val);
Node copyNode = new Node();
copyNode.val = node.val;
visited.put(node.val, copyNode);
for (Node neighbor : node.neighbors) {
copyNode.neighbors.add(cloneGraph(neighbor));
}
return copyNode;
}
}