【leetcode】No.133:clone-graph

题目描述

Clone an undirected graph. Each node in the graph contains alabeland a list of itsneighbors.

OJ's undirected graph serialization:
Nodes are labeled uniquely.

We use#as a separator for each node, and,as a separator for node label and each neighbor of the node.

As an example, consider the serialized graph{0,1,2# 1,2# 2,2}.

The graph has a total of three nodes, and therefore contains three parts as separated by#.

First node is labeled as0. Connect node0to both nodes1and2.
Second node is labeled as1. Connect node1to node2.
Third node is labeled as2. Connect node2to node2(itself), thus forming a self-cycle.

Visually, the graph looks like the following:

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

思路:

BFS,主要需要把新节点用map存起来,到后来找邻居的时候先到map中去找,而不是每次都新建节点

代码:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Queue;
/**
 * Definition for undirected graph.
 * class UndirectedGraphNode {
 *     int label;
 *     ArrayList neighbors;
 *     UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList(); }
 * };
 */
public class Solution {
    public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
        if (node == null) return null;
        Queue queue = new LinkedList();
        HashMap map = new HashMap();
        UndirectedGraphNode res = new UndirectedGraphNode(node.label);
        map.put(res.label, res);
        queue.offer(node);
        while (!queue.isEmpty()){
            UndirectedGraphNode tmp = queue.poll();
            // 从map中找到原来节点的clone
            UndirectedGraphNode newNode = map.get(tmp.label);
            for (UndirectedGraphNode neighbor : tmp.neighbors){
                // 对map中不存在的邻居节点,新建一个节点放进去,并放入队列中
                if (!map.containsKey(neighbor.label)){
                    map.put(neighbor.label, new UndirectedGraphNode(neighbor.label));
                    queue.offer(neighbor);
                }
                // 拿到clone节点的邻居放入邻居列表中
                newNode.neighbors.add(map.get(neighbor.label));
            }
        }
        return res;
    }
}

你可能感兴趣的:(【leetcode】No.133:clone-graph)