Learn Simpli

Free Online Tutorial For Programmers, Contains a Solution For Question in Programming. Quizzes and Practice / Company / Test interview Questions.

Graph

data structure - graph

Introduction
  1. Is a group of vertices and edges that are used to connect these vertices
  2. Each item is called node or vertex
  3. Edges connect the nodes
Write a code
Let’s write a code in javascript
// Graph in javascript
  class Graph {
    constructor() {
        this.numberOfNodes = 0;
        this.adjacentList = {};
    }
    addVertex(node) {
        this.adjacentList[node] = [];
        this.numberOfNodes++;
    }
    addEdge(node1, node2) {
        this.adjacentList[node1].push(node2);
        this.adjacentList[node2].push(node1);
    }
    printConnections() {
        const availabelNodes = Object.keys(this.adjacentList);
        for (let node of availabelNodes) {
            let nodeConnections = this.adjacentList[node];
            let connections = "";
            let vertex;
            for (vertex of nodeConnections) {
                connections += vertex + " ";
            }
            console.log(node + "-->" + connections);
        }
    }
}

let graphInstance = new Graph();
graphInstance.addVertex('1');
graphInstance.addVertex('2');
graphInstance.addVertex('3');
graphInstance.addVertex('4');
graphInstance.addVertex('5');
graphInstance.addVertex('6');
graphInstance.addVertex('7');
graphInstance.addEdge('4', '1');
graphInstance.addEdge('5', '4');
graphInstance.addEdge('6', '2');
graphInstance.addEdge('5', '5');
graphInstance.addEdge('2', '2');
graphInstance.printConnections();
// Output
//1-->4 
// 2-->6 2 2 
// 3-->
// 4-->1 5 
// 5-->4 5 5 
// 6-->2 
// 7-->