137. Clone Graph——克隆图(BFS宽度优先搜索)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lighthear/article/details/79736707

Description

克隆一张无向图,图中的每个节点包含一个 label 和一个列表 neighbors

数据中如何表示一个无向图?http://www.lintcode.com/help/graph/

你的程序需要返回一个经过深度拷贝的新图。这个新图和原图具有同样的结构,并且对新图的任何改动不会对原图造成任何影响。

样例

比如,序列化图 {0,1,2#1,2#2,2} 共有三个节点, 因此包含两个个分隔符#。

  1. 第一个节点label为0,存在边从节点0链接到节点1和节点2
  2. 第二个节点label为1,存在边从节点1连接到节点2
  3. 第三个节点label为2,存在边从节点2连接到节点2(本身),从而形成自环。

我们能看到如下的图:

   1
  / \
 /   \
0 --- 2
     / \
     \_/
Solution

这道题使用宽度优先搜索的思想,分为三个步骤来解决。

1.从一个点出发,使用BFS找到所有的点。(使用queue和set)

2.复制所有的点,并用map保留原图点和新图点之间的映射关系。

3.复制所有的边。遍历原图中每个点的邻居节点,并根据映射关系添加到新图中该节点的邻居节点列表中。

/**
 * Definition for undirected graph.
 * class UndirectedGraphNode {
 *     int label;
 *     ArrayList<UndirectedGraphNode> neighbors;
 *     UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); }
 * };
 */


public class Solution {
    /*
     * @param node: A undirected graph node
     * @return: A undirected graph node
     */
    public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
        // write your code here
        //用3个步骤:
        //1.从1个点找到所有点
        //2.复制所有的点
        //3.复制所有的边
        if (node == null) {
            return null;
        }
        
        // use bfs algorithm to traverse the graph and get all nodes.
        ArrayList<UndirectedGraphNode> nodes = getNodes(node);
        
        // copy nodes, store the old->new mapping information in a hash map
        HashMap<UndirectedGraphNode, UndirectedGraphNode> mapping = new HashMap<>();
        //创建新的节点,并建立原图点和新图点之间的映射关系存在HashMap中
        for (UndirectedGraphNode n : nodes) {
            mapping.put(n, new UndirectedGraphNode(n.label));
        }
        
        // copy neighbors(edges)
        for (UndirectedGraphNode n : nodes) {
            //遍历原图点并根据映射关系找到新图对应的点
            UndirectedGraphNode newNode = mapping.get(n);
            //遍历原图点的邻居节点,并根据映射关系找到新图中对应的新节点
            for (UndirectedGraphNode neighbor : n.neighbors) {
                UndirectedGraphNode newNeighbor = mapping.get(neighbor);
                newNode.neighbors.add(newNeighbor); //将对应的新节点位置信息,添加到该点的邻居列表中
            }
        }
        return mapping.get(node);   //返回原头节点对应的新节点
    }
    private ArrayList<UndirectedGraphNode> getNodes(UndirectedGraphNode node) {
        //使用宽度优先搜索的方法找到所有节点
        Queue<UndirectedGraphNode> queue = new LinkedList<>();
        HashSet<UndirectedGraphNode> set = new HashSet<>();
        
        queue.offer(node);
        set.add(node);
        while (!queue.isEmpty()) {
            UndirectedGraphNode head = queue.poll();
            for (UndirectedGraphNode neighbor : head.neighbors) {
                if (!set.contains(neighbor)) {
                    set.add(neighbor);
                    queue.offer(neighbor);
                }
            }
        }
        return new ArrayList<>(set);
    }
}



猜你喜欢

转载自blog.csdn.net/lighthear/article/details/79736707
今日推荐