java BFS solution


  • 0
    2
    /**
     * Definition for undirected graph.
     * class UndirectedGraphNode {
     *     int label;
     *     List<UndirectedGraphNode> neighbors;
     *     UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); }
     * };
     */
    public class Solution {
        public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
            if (node == null) {
                return null;
            }
            HashMap<Integer, UndirectedGraphNode> map = new HashMap<Integer, UndirectedGraphNode>();
            Queue<UndirectedGraphNode> q = new LinkedList<UndirectedGraphNode>();
            q.add(node);
            map.put(node.label, new UndirectedGraphNode(node.label));
            while (!q.isEmpty()) {
                UndirectedGraphNode ugn = q.remove();
                UndirectedGraphNode copy = map.get(ugn.label);
                for (UndirectedGraphNode adj : ugn.neighbors) {
                    if (!map.containsKey(adj.label)) {
                        map.put(adj.label, new UndirectedGraphNode(adj.label));
                        q.add(adj);
                    }
                    copy.neighbors.add(map.get(adj.label));
                }
            }
            return map.get(node.label);
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.