A reason you get run time error for {-1}


  • 0
    A

    Firstly, {-1} means a graph with only one node, labeled -1 and no neighbors.

    I used a pointer to point to my newly created first node, and return that point after I cloned whole graph, then I get run time error for {-1} case. Apparently the test code check if you use reference more strictly than it should be.

    Here's my code that got run time error, if you change last line return head to return map[node] it will be accepted.

            if(!node) return node;
            queue<UndirectedGraphNode *> q;
            unordered_map<UndirectedGraphNode*, UndirectedGraphNode*> map;
            UndirectedGraphNode* head;
            q.push(node);
            while(!q.empty()){
                UndirectedGraphNode * old = q.front();
                q.pop();
    
                vector<UndirectedGraphNode *> oldNeighbors = old->neighbors;
                vector<UndirectedGraphNode *> newNeighbors;
                UndirectedGraphNode* newNode;
                
                if(map.find(old)==map.end()){
                    newNode = new UndirectedGraphNode(old->label);
                    map[old] = newNode;
                    if(!head) head = newNode;
                }else
                    newNode = map[old];
                    
                for(UndirectedGraphNode* oldNei: oldNeighbors){
                        UndirectedGraphNode* newNei;
                        if(map.find(oldNei)==map.end()){
                            newNei = new UndirectedGraphNode(oldNei->label);
                            map[oldNei] = newNei;
                            q.push(oldNei);
                        }else{
                            newNei = map[oldNei];
                        }
                        newNeighbors.push_back(newNei);
                }
                newNode->neighbors = newNeighbors;
            }
            
            return head;

Log in to reply
 

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