【BFS】LeetCode 133. 克隆图

题目链接

133. 克隆图

思路

通过 HashMap 存储原结点与克隆结点的对应关系,这样在 BFS 遍历图的过程中,能够很方便找到该结点对应的克隆结点,并修改克隆结点的邻接表。

代码

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

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

        queue.add(node);
        visited.put(node, new Node(node.val, new ArrayList()));
        while(!queue.isEmpty()){
            Node n = queue.remove();
            for(Node neighbor : n.neighbors){
                if(!visited.containsKey(neighbor)){
                    visited.put(neighbor, new Node(neighbor.val, new ArrayList()));
                    queue.add(neighbor);
                }
                // renew current node's neighbor list
                visited.get(n).neighbors.add(visited.get(neighbor));
            }
        }

        return visited.get(node);
    }
}
posted @ 2023-01-12 21:43  Frodo1124  阅读(30)  评论(0编辑  收藏  举报