其他分享
首页 > 其他分享> > LeetCode 0133 Clone Graph

LeetCode 0133 Clone Graph

作者:互联网

原题传送门

1. 题目描述


2. Solution 1

1、思路分析
DFS

2、代码实现

package Q0199.Q0133CloneGraph;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/*
    DFS
 */
public class Solution {

    private Map<Integer, Node> seen = new HashMap<>();

    public Node cloneGraph(Node node) {
        if (node == null) return null;
        if (seen.containsKey(node.val)) return seen.get(node.val);

        Node newNode = new Node(node.val, new ArrayList<>());
        seen.put(newNode.val, newNode);
        for (Node neighbor : node.neighbors)
            newNode.neighbors.add(cloneGraph(neighbor));
        return newNode;
    }
}

3、复杂度分析
时间复杂度: O(n)
空间复杂度: O(n)

3. Solution 2

1、思路分析
BFS

2、代码实现

package Q0199.Q0133CloneGraph;

import java.util.*;

/*
    BFS:
 */
public class Solution2 {

    private Map<Node, Node> seen = new HashMap<>();

    public Node cloneGraph(Node node) {
        if (node == null) return null;

        Node copy = new Node(node.val, new ArrayList<>());
        seen.put(node, copy);

        Queue<Node> queue = new ArrayDeque<>();
        queue.add(node);
        while (!queue.isEmpty()) {
            Node cur = queue.poll();
            for (Node neighbor : cur.neighbors) {
                if (!seen.containsKey(neighbor)) {
                    seen.put(neighbor, new Node(neighbor.val, new ArrayList<>()));
                    queue.add(neighbor);
                }
                seen.get(cur).neighbors.add(seen.get(neighbor));
            }
        }
        return copy;
    }
}

3、复杂度分析
时间复杂度: O(n)
空间复杂度: O(n)

标签:Node,node,复杂度,Graph,Clone,neighbor,new,seen,LeetCode
来源: https://www.cnblogs.com/junstat/p/16291032.html