LeetCode-克隆圖

輸入:adjList = [[2,4],[1,3],[2,4],[1,3]]
輸出:[[2,4],[1,3],[2,4],[1,3]]
解釋:
圖中有 4 個節點。
節點 1 的值是 1,它有兩個鄰居:節點 2 和 4 。
節點 2 的值是 2,它有兩個鄰居:節點 1 和 3 。
節點 3 的值是 3,它有兩個鄰居:節點 2 和 4 。
節點 4 的值是 4,它有兩個鄰居:節點 1 和 3 。

DFS:

HashMap<Node,Node> visited = new HashMap<Node, Node>();

    public Node cloneGraph(Node node) {

        if (node == null){
            return null;
        }

        if (visited.containsKey(node)){
            return visited.get(node);
        }

        List<Node> neighbors = node.neighbors;
        int val = node.val;

        Node finalNode = new Node(val);
        visited.put(node,finalNode);
        for (int i = 0; i < neighbors.size(); i++){
            Node node1 = neighbors.get(i);
            Node node2 = cloneGraph(node1);
            finalNode.neighbors.add(node2);
        }

        return finalNode;

    }

BFS:

從隊列首部取出一個節點。
遍歷該節點的所有鄰接點。
如果某個鄰接點已被訪問,則該鄰接點一定在 visited 中,那麼從 visited 獲得該鄰接點。
否則,創建一個新的節點存儲在 visited 中。
將克隆的鄰接點添加到克隆圖對應節點的鄰接表中。

/*
// 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 {


    public Node cloneGraph(Node node) {

       if (node == null) {
            return node;
        }

        // Hash map to save the visited node and it's respective clone
        // as key and value respectively. This helps to avoid cycles.
        HashMap<Node, Node> visited = new HashMap();

        // Put the first node in the queue
        LinkedList<Node> queue = new LinkedList<Node> ();
        queue.add(node);
        // Clone the node and put it in the visited dictionary.
        visited.put(node, new Node(node.val, new ArrayList()));

        // Start BFS traversal
        while (!queue.isEmpty()) {
            // Pop a node say "n" from the from the front of the queue.
            Node n = queue.remove();
            // Iterate through all the neighbors of the node "n"
            for (Node neighbor: n.neighbors) {
                if (!visited.containsKey(neighbor)) {
                    // Clone the neighbor and put in the visited, if not present already
                    visited.put(neighbor, new Node(neighbor.val, new ArrayList()));
                    // Add the newly encountered node to the queue.
                    queue.add(neighbor);
                }
                // Add the clone of the neighbor to the neighbors of the clone node "n".
                visited.get(n).neighbors.add(visited.get(neighbor));
            }
        }

        // Return the clone of the node from visited.
        return visited.get(node);

    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章