Graphs-DSA

Graphs in Data Structures and Algorithms

A graph is a non-linear data structure consisting of vertices (nodes) and edges (links between nodes).

Graphs are used to represent real-world relationships where data has connections to other data. Some examples of graph applications are:

  • Social networks - Users are vertices and friend connections are edges

  • Route finding - Locations are vertices and routes are edges

  • Recommendation systems - Items are vertices and similarities are edges

Representation

Graphs are typically represented using two methods:

  1. Adjacency matrix - A 2D array of size V x V where V is the number of vertices. The value at [i][j] indicates if there is an edge between vertex i and j.
0 1 0 1 
1 0 0 0
0 0 0 1
1 0 1 0
  1. Adjacency list - An array of lists, where each index corresponds to a vertex and the list contains the vertices adjacent to that vertex.
[1, 3]  
[0]
[3]
[0, 2]

The adjacency matrix uses more space but edge lookup is faster. The adjacency list uses less space but edge lookup is slower.

Operations

Common operations on graphs are:

  • Traversals - Breadth-first search (BFS) and Depth-first search (DFS)

  • Finding paths between vertices

  • Minimum spanning tree - Prim's and Kruskal's algorithms

  • Shortest path - Dijkstra's and Bellman-Ford's algorithms

Example Code

Here is the adjacency list representation in Python:

graph = [[1,3], [0], [3], [0,2]]

# BFS 
def BFS(s): 
    visited = [False] * len(graph)

    queue = [s] 
    visited[s] = True

    while queue:
        node = queue.pop(0) 
        # visit node...
        for neighbour in graph[node]:
            if not visited[neighbour]:
                visited[neighbour] = True
                queue.append(neighbour)

Hope this helps! Let me know if you have any other questions.

Did you find this article valuable?

Support Bandari sai kumar by becoming a sponsor. Any amount is appreciated!