10-line JAVA DFS Solution

  • 1
    public class Solution {
        public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
            Map<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<>();
            return dfs(node, map);
        public UndirectedGraphNode dfs(UndirectedGraphNode node, Map<UndirectedGraphNode, UndirectedGraphNode> map) {
            if (node == null) return null;
            if (map.containsKey(node)) return map.get(node);
            else {
                map.put(node, new UndirectedGraphNode(node.label));
                for (UndirectedGraphNode n: node.neighbors) map.get(node).neighbors.add(dfs(n, map));
            return map.get(node);

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.