Java BFS solution

  • 29
    public UndirectedGraphNode cloneGraph(UndirectedGraphNode root) {
      if (root == null) return null;
      // use a queue to help BFS
      Queue<UndirectedGraphNode> queue = new LinkedList<UndirectedGraphNode>();
      // use a map to save cloned nodes
      Map<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<UndirectedGraphNode, UndirectedGraphNode>();
      // clone the root
      map.put(root, new UndirectedGraphNode(root.label));
      while (!queue.isEmpty()) {
        UndirectedGraphNode node = queue.poll();
        // handle the neighbors
        for (UndirectedGraphNode neighbor : node.neighbors) {
          if (!map.containsKey(neighbor)) {
            // clone the neighbor
            map.put(neighbor, new UndirectedGraphNode(neighbor.label));
            // add it to the next level
          // copy the neighbor
      return map.get(root);

Log in to reply

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