A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/implementation-graph-javascript/ below:

Implementation of Graph in JavaScript

Implementation of Graph in JavaScript

Last Updated : 12 Jun, 2024

Implementing graphs in JavaScript is crucial for visualizing data structures and relationships. JavaScript provides various ways to create and manage graphs, including adjacency lists, adjacency matrices, and edge lists. This guide will cover the basics of graph implementation in JavaScript, demonstrating how to represent and traverse graphs using these methods. Whether you're building a network visualization, a recommendation system, or a pathfinding algorithm, understanding graph implementation will enhance your JavaScript development skills.

In this article, we would be implementing the Graph data structure in JavaScript. The graph is a non-linear data structure. Graph G contains a set of vertices V and a set of Edges E. Graph has lots of applications in computer science. 

Graph is Divided into Two Broad Categories

There are various ways to represent a Graph:-

There are several other ways like incidence matrix, etc. but these two are most commonly used. Refer to Graph and its representations for the explanation of the Adjacency matrix and list.

In this article, we would be using Adjacency List to represent a graph because in most cases it has a certain advantage over the other representation. 

Now Let's see an example of Graph class- 

JavaScript
// create a graph class
class Graph {
    // defining vertex array and
    // adjacent list
    constructor(noOfVertices)
    {
        this.noOfVertices = noOfVertices;
        this.AdjList = new Map();
    }

    // functions to be implemented

    // addVertex(v)
    // addEdge(v, w)
    // printGraph()

    // bfs(v)
    // dfs(v)
}

The above example shows a framework of Graph class. We define two private variables i.e noOfVertices to store the number of vertices in the graph and AdjList, which stores an adjacency list of a particular vertex.We used a Map Object provided by ES6 in order to implement the Adjacency list. Where the key of a map holds a vertex and values hold an array of an adjacent node.

Now let's implement functions to perform basic operations on the graph: 

JavaScript
// add vertex to the graph
addVertex(v)
{
    // initialize the adjacent list with a
    // null array
    this.AdjList.set(v, []);
}
JavaScript
// add edge to the graph
addEdge(v, w)
{
    // get the list for vertex v and put the
    // vertex w denoting edge between v and w
    this.AdjList.get(v).push(w);

    // Since graph is undirected,
    // add an edge from w to v also
    this.AdjList.get(w).push(v);
}
JavaScript
// Prints the vertex and adjacency list
printGraph()
{
    // get all the vertices
    var get_keys = this.AdjList.keys();

    // iterate over the vertices
    for (var i of get_keys) 
{
        // get the corresponding adjacency list
        // for the vertex
        var get_values = this.AdjList.get(i);
        var conc = "";

        // iterate over the adjacency list
        // concatenate the values into a string
        for (var j of get_values)
            conc += j + " ";

        // print the vertex and its adjacency list
        console.log(i + " -> " + conc);
    }
}

Now we will use the graph class to implement the graph shown above: 

JavaScript
// Using the above implemented graph class
var g = new Graph(6);
var vertices = [ 'A', 'B', 'C', 'D', 'E', 'F' ];

// adding vertices
for (var i = 0; i < vertices.length; i++) {
    g.addVertex(vertices[i]);
}

// adding edges
g.addEdge('A', 'B');
g.addEdge('A', 'D');
g.addEdge('A', 'E');
g.addEdge('B', 'C');
g.addEdge('D', 'E');
g.addEdge('E', 'F');
g.addEdge('E', 'C');
g.addEdge('C', 'F');

// prints all vertex and
// its adjacency list
// A -> B D E
// B -> A C
// C -> B E F
// D -> A E
// E -> A D F C
// F -> E C
g.printGraph();

Graph Traversal

We will implement the most common graph traversal algorithm: 

Implementation of BFS and DFS: 

JavaScript
// function to performs BFS
bfs(startingNode)
{

    // create a visited object
    var visited = {};

    // Create an object for queue
    var q = new Queue();

    // add the starting node to the queue
    visited[startingNode] = true;
    q.enqueue(startingNode);

    // loop until queue is empty
    while (!q.isEmpty()) {
        // get the element from the queue
        var getQueueElement = q.dequeue();

        // passing the current vertex to callback function
        console.log(getQueueElement);

        // get the adjacent list for current vertex
        var get_List = this.AdjList.get(getQueueElement);

        // loop through the list and add the element to the
        // queue if it is not processed yet
        for (var i in get_List) {
            var neigh = get_List[i];

            if (!visited[neigh]) {
                visited[neigh] = true;
                q.enqueue(neigh);
            }
        }
    }
}
JavaScript
// prints
// BFS
// A B D E C F
console.log("BFS");
g.bfs('A');

JavaScript
// Main DFS method
dfs(startingNode)
{

    var visited = {};

    this.DFSUtil(startingNode, visited);
}

// Recursive function which process and explore
// all the adjacent vertex of the vertex with which it is called
DFSUtil(vert, visited)
{
    visited[vert] = true;
    console.log(vert);

    var get_neighbours = this.AdjList.get(vert);

    for (var i in get_neighbours) {
        var get_elem = get_neighbours[i];
        if (!visited[get_elem])
            this.DFSUtil(get_elem, visited);
    }
}
JavaScript
// prints
// DFS
// A B C E D F
console.log("DFS");
g.dfs('A');

Time Complexity:  O(V + E), where V is the number of vertices and E is the number of edges in the graph.
Auxiliary Space: O(V), since an extra visited array of size V is required.

Graph implementation in JavaScript opens up numerous possibilities for data visualization and complex problem-solving. By using adjacency lists, matrices, and edge lists, you can effectively represent and traverse graphs. This foundational knowledge is essential for developing advanced applications like social networks, route planners, and more. Start incorporating these techniques into your projects to leverage the full potential of graph data structures in JavaScript.



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4