I tested this test case on my local machine but it doesn't pass OJ

  • 0
    public class Solution {
        public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
            if (node == null) return node;
            HashMap<Integer, UndirectedGraphNode> hm = new HashMap<Integer, UndirectedGraphNode>();
            HashSet<UndirectedGraphNode> copied = new HashSet<UndirectedGraphNode>();
            HashSet<UndirectedGraphNode> visited = new HashSet<UndirectedGraphNode>();
            LinkedList<UndirectedGraphNode> queue = new LinkedList<UndirectedGraphNode>();
            while (!queue.isEmpty()) {
                UndirectedGraphNode orig = queue.remove();
                List<UndirectedGraphNode> neighbors = orig.neighbors;
                UndirectedGraphNode copy = new UndirectedGraphNode(orig.label);
                if (hm.containsKey(orig.label)) copy = hm.get(orig.label);
                else hm.put(orig.label, copy);
                for (UndirectedGraphNode nb : neighbors) {
                    UndirectedGraphNode copyNB = new UndirectedGraphNode(nb.label);
                    if (!hm.containsKey(nb.label)) hm.put(nb.label, copyNB);
                    else copyNB = hm.get(nb.label);
                    if (!copied.contains(nb)) {
                        if (copy == copyNB) copy.neighbors.add(copy);
                        else {
                    if (!visited.contains(nb)) {
            return hm.get(node.label);

    Based on BFS and visited to avoid re enque original nodes, HashMap and copied to keep track of what's been copied. Code maybe not elegant but I hope my logic is right.
    However, this case is not passing

    Input: {-1,1#1}
    Output: {-1,1,1#1}
    Expected: {-1,1#1}

    Seems but when I ran on the local machine everything was fine. Can someone please help?

  • 0

    Are you printing the result in the serialized format ? Can you try putting a debug point in your code and verify the result in the debugger.

Log in to reply

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