Problem

Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.

JavaScript Code

function UndirectedGraphNode(value, nebrs) {
    this.val = value;
    if(nebrs != null) {
        this.neighbors = nebrs; 
    } else {
        this.neighbors = [];
    }
    this.visited = false;
}

UndirectedGraphNode.prototype = {
        constructor: UndirectedGraphNode
}

function cloneGraph(node) {
    if(node == null)
        return null;

    var queue = [];
    var map = {};

    var newHead = new UndirectedGraphNode(node.val, node.neighbors);

    queue.push(node);
    map[node.val] = newHead;

    while(queue.length != 0){
        var curr = queue.shift();
        var currNeighbors = curr.neighbors; 

        for(var aNeighbor in currNeighbors){
            if(map[aNeighbor.val]==null){
                var copy = new UndirectedGraphNode(node.val, node.neighbors);
                map[aNeighbor.val] = copy;
                map[curr.val].neighbors.push(copy);
                queue.push(aNeighbor);
            }else{
                map[curr.val].neighbors.push(map[aNeighbor.val]);
            }
        }

    }
    return newHead;
}

6 comments:

  1. Requirement for custom application development has risen today with increment in the quantity of PDA clients. custom javascript development company can enable organizations to connect with their customers in less demanding ways.

    ReplyDelete
  2. As Indicated by the Best video javascript development company As we probably am aware there is an eager market for gaming on the web, on handheld gadgets and consoles alike. Individuals who profit, however as we might find in the development and extension of Open source diversions the motivators and inspirations to grow are substantially less fulfilling, unless obviously you bolster testing Mac's one-sided nearness.

    ReplyDelete
  3. White Label Forex Broker Meaning is a comprehensive guide to deciding on the best Forex Brokers, Trading Costs and Fees. Find out which brokers offer the best value for money?

    ReplyDelete
  4. Free Forex White Label Partnership is the next step in our Forex Trading Education products. The course was designed to be modern and easy to use so that it can be learned by anyone, at any computer, while still allowing your customers to interact with you remotely.

    ReplyDelete
  5. Cheapest White Label Forex Broker is a booming online business that allows you to leverage the skills and knowledge of expert traders to improve your own trading results.

    ReplyDelete

Blogroll

Popular Posts