当前位置:网站首页>Digraph deep copy

Digraph deep copy

2022-06-12 21:34:00 Besieged city_ city with high walls

Undirected graph node 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;
    }
}

Mode one , Depth first traversal algorithm copy :

class Solution {
    
	// Store the visited nodes and their copies 
    private HashMap <Node, Node> visited = new HashMap <> ();
    
    public Node cloneGraph(Node node) {
    
        if (node == null) {
    
            return node;
        }

        //  If the node has been accessed , The corresponding clone node is directly extracted from the hash table and returned to 
        if (visited.containsKey(node)) {
    
            return visited.get(node);
        }

        //  Clone node , Notice that we won't clone the list of its neighbors for deep copy 
        Node cloneNode = new Node(node.val, new ArrayList());
        //  Hash table storage 
        visited.put(node, cloneNode);

        //  Traverse the neighbors of the node and update the neighbor list of the clone node 
        for (Node neighbor: node.neighbors) {
    
            cloneNode.neighbors.add(cloneGraph(neighbor));
        }
        return cloneNode;
    }
}

Mode two 、 Breadth first traversal algorithm copy :

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

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

        //  Add the node given the topic to the queue 
        LinkedList<Node> queue = new LinkedList<Node> ();
        queue.add(node);
        //  Clone the first node and store it in the hash table 
        visited.put(node, new Node(node.val, new ArrayList()));

        //  Breadth first search 
        while (!queue.isEmpty()) {
    
            //  Take out the head node of the queue 
            Node n = queue.remove();
            //  Traverse the neighbors of the node 
            for (Node neighbor: n.neighbors) {
    
                if (!visited.containsKey(neighbor)) {
    
                    //  If you haven't been interviewed , Just clone and store it in the hash table 
                    visited.put(neighbor, new Node(neighbor.val, new ArrayList()));
                    //  Add neighbor nodes to the queue 
                    queue.add(neighbor);
                }
                //  Update the neighbor list of the current node 
                visited.get(n).neighbors.add(visited.get(neighbor));
            }
        }

        return visited.get(node);
    }
}
原网站

版权声明
本文为[Besieged city_ city with high walls]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/163/202206122125175587.html