Skip to main content

Graph Data Structure

Graph

Graph data structure

A graph can be defined as a group of vertices and edges that are used to connect these vertices. A graph can be seen as a cyclic tree, where the vertices (Nodes) maintain any complex relationship among them instead of having parent child relationship.

A graph G can be defined as an ordered set G(V, E) where V(G) represents the set of vertices and E(G) represents the set of edges which are used to connect these vertices. A Graph G(V, E) with 5 vertices (A, B, C, D, E) and six edges ((A,B), (B,C), (C,E), (E,D), (D,B), (D,A)) is shown in the following figure.

Directed and undirected graph

A graph can be directed or undirected. However, in an undirected graph, edges are not associated with the directions with them. An undirected graph does not have any edges in directions. If an edge exists between vertex A and B then the vertices can be traversed from B to A as well as A to B.

In a directed graph, edges form an ordered pair. Edges represent a specific path from some vertex A to another vertex B. Node A is called the initial node while node B is called the terminal node.

Graph terminology

Path

A path can be defined as the sequence of nodes that are followed in order to reach some terminal node V from the initial node U.

Closed Path

A path will be called a closed path if the initial node is the same as the terminal node. A path will be a closed path if V0=VN.

Simple Path If all the nodes of the graph are distinct with an exception V0=VN, then such path P is called as closed simple path.

Cycle

A cycle can be defined as the path which has no repeated edges or vertices except the first and last vertices.

Connected Graph

A connected graph is the one in which some path exists between every two vertices (u, v) in V. There are no isolated nodes in the connected graph.

Complete Graph

A complete graph is the one in which every node is connected with all other nodes. A complete graph contains n(n-1)/2 edges where n is the number of nodes in the graph.

Weighted Graph

In a weighted graph, each edge is assigned with some data such as length or weight. The weight of an edge e can be given as w(e) which must be a positive (+) value indicating the cost of traversing the edge.

Digraph

A digraph is a directed graph in which each edge of the graph is associated with some direction and the traversing can be done only in the specified direction.

Adjacent Nodes

If two nodes u and v are connected via an edge e, then the nodes u and v are called neighbours or adjacent nodes.

Degree of the Node

A degree of a node is the number of edges that are connected with that node. A node with degree 0 is called an isolated node.

Graph Representation

By Graph representation, we simply mean the technique which is to be used in order to store some graphs into the computer's memory.

There are two ways to store Graph into the computer's memory. In this part of this tutorial, we discuss each one of them in detail.

1. Sequential Representation

In sequential representation We use an adjacency matrix to store the mapping represented by vertices and edges. In the adjacency matrix, the rows and columns are represented by the graph vertices. A graph having n vertices, will have a dimension n x n.

Representation of weighted directed graph

Representation of weighted directed graphs is different. Instead of filling the entry by 1, the Non- zero entries of the adjacency matrix are represented by the weight of respective edges.

Directed graph

In a directed graph, the sum of lengths of all the adjacency lists is equal to the number of edges present in the graph. In the case of weighted directed graphs, each node contains an extra field that is called the weight of the node. The adjacency list representation of a directed graph is shown in the following figure.

Adjacency matrix

Adjacency Matrix is a 2D array of size V x V where V is the number of vertices in a graph. Let the 2D array be adj[][], a slot adj[i][j] = 1 indicates that there is an edge from vertex i to vertex j. Adjacency matrix for undirected graph is always symmetric. Adjacency Matrix is also used to represent weighted graphs. If adj[i][j] = w, then there is an edge from vertex i to vertex j with weight.

Adjacency multi list

It is represented by M Vertex-1 Vertex-2 List-1 List-2 Where M = Visited Vertex -1 = start vertex of edge (m,n) = m Vertex-2 = start vertex of edge (m,n) = n List -1 = List where vertex 1 is present List -2= List where vertex 2 is present

Graph traversal

Traversing the graph means examining all the nodes and vertices of the graph. There are two standard methods by which we can traverse the graphs. Let's discuss each one of them in detail.

  • Breadth First Search
  • Depth First Search

Breadth first search

Breadth first search is a graph traversal algorithm that starts traversing the graph from the root node and explores all the neighboring nodes. Then, it selects the nearest node and explores all the unexplored nodes.

The algorithm follows the same process for each of the nearest nodes until it finds the goal. The algorithm of breadth first search is given below. The algorithm starts with examining the node A and all of its neighbours.

In the next step, the neighbours of the nearest node of A are explored and the process continues in the further steps. The algorithm explores all neighbours of all the nodes and ensures that each node is visited exactly once and no node is visited twice.

Breadth first search is a graph traversal algorithm that starts traversing the graph from the root node and explores all the neighboring nodes. Then, it selects the nearest node and explores all the unexplored nodes.

The algorithm follows the same process for each of the nearest nodes until it finds the goal. The algorithm of breadth first search is given below. The algorithm starts with examining the node A and all of its neighbours.

In the next step, the neighbours of the nearest node of A are explored and the process continues in the further steps. The algorithm explores all neighbours of all the nodes and ensures that each node is visited exactly once and no node is visited twice.

Depth First Search algorithm

is a recursive algorithm that uses the idea of backtracking. It involves exhaustive searches of all the nodes by going ahead, if possible, else by backtracking.

Here, the word backtrack means that when you are moving forward and there are no more nodes along the current path, you move backwards on the same path to find nodes to traverse. All the nodes will be visited on the current path till all the unvisited nodes have been traversed after which the next path will be selected.

The purpose of the algorithm is to mark each vertex as visited while avoiding cycles. The DFS algorithm works as follows:

  • Start by putting any one of the graph's vertices on top of a stack.
  • Take the top item of the stack and add it to the visited list.
  • Create a list of that vertex's adjacent nodes. Add the ones which aren't in the visited list to the top of the stack.
  • Keep repeating steps 2 and 3 until the stack is empty.

Comments

Trending⚡

Understanding link.click() in JavaScript

Hey! Today i am going to share with you how to use link.click() function in javascript As a JavaScript developer, you may come across the need to programmatically click a link on a web page. The link.click() method is a commonly used way to do this, and it is important to understand how it works and when to use it. What is link.click()? link.click() is a method that can be used to simulate a click on a link element in JavaScript. It is typically used when you want to trigger a link click event programmatically, rather than requiring the user to physically click the link. How to use link.click() Using link.click() is relatively straightforward. First, you need to select the link element you want to click using a DOM selector such as getElementById() or querySelector(). Then, you can call the click() method on the link element to simulate a click. Here is an example: // select the link element const myLink = document.getElementById('my-link'); // simulate a cl...

How to Create Studio Ghibli-Style AI Images on ChatGPT for Free

How to Create Studio Ghibli-Style AI Images on ChatGPT for Free AI-generated art is making waves across the internet, captivating audiences with stunning, ethereal visuals inspired by the iconic animation style of Studio Ghibli . These AI-crafted images, from dreamy landscapes to expressive characters, reflect the timeless magic of Hayao Miyazaki ’s beloved films such as Spirited Away , My Neighbor Totoro , and Howl’s Moving Castle . Thanks to recent advancements in AI technology, particularly OpenAI ’s latest ChatGPT update, users can now create their own Studio Ghibli-inspired illustrations effortlessly by entering simple text prompts. This exciting feature is transforming digital art creation and making it accessible to both professionals and beginners. In this article, we’ll guide you through creating Ghibli-style AI images using ChatGPT and explore free alternatives for users who don’t yet have access to this feature. Ghibli AI generator free Step-by-Step Guide: How to Crea...

Value Model vs Reference Model

Value Model vs Reference Model In programming languages, two different models are used for variables.  These are:  Value Model  A variable contains a value. The name of the variable gives its value.  Reference Model A variable contains (say y) refers to another variable (say x) with a value. The variable ‘y’ is used to access the value of ‘x’ indirectly.  The ‘C’ language is based on value model. However, by using pointers, we can implement the reference model. The pointer is used to access the value of a variable indirectly. Also Read Static and Dynamic Memory Allocation Memory Leak and Dangling Pointer Memory Allocation for 2D Array Dynamic Memory Allocation Pointer Constant and Constant Pointer Pointer Declarations and their Meanings Functions and Pointers Initializing Pointer to Pointer Pointer to Pointer Multiple Indirection Relationship between Array and Pointer Pointer to Array Pointer Arithmetic Types of Pointer Illustrat...

How to write programs in Bhai language

Bhai Language Bhai language is fun Programming language , with this language you can makes jokes in hindi. Bhai language written in typescript. It's very funny , easy and amazing language. Keywords of this language written in Hindi . Starting and ending of the program Start program with keyword " hi bhai " and end with " bye bhai ". It's compulsory to add this keyword before starting and end on the program. You write your programming logic inside this hi bhai and bye bhai . How to declare variables in Bhai language We use " bhai ye hai variable_name" keyword for declaring variables. In javascript we use var keyword for declaring variables but here you have to use " bhai ye hai " keyword. If you are declaring string then use " " double quotes. You can use Boolean variable like sahi and galat for true and false . How to print output in Bhai language You have to use " bol bhai " keyword for ...

ChatGPT Now Allows Free Users to Create Ghibli-Style AI Images – Here’s How

OpenAI has finally expanded its native image generation feature to free ChatGPT users, allowing them to transform images into stunning Studio Ghibli-style artwork . While the company has yet to make an official announcement, multiple tests using free ChatGPT accounts confirm that the feature is now accessible without requiring a paid subscription. Ghibli AI Images Now Available for Free Users Previously, OpenAI restricted its image generation capabilities to ChatGPT Plus, Pro, and Team users. This led free-tier users to seek alternatives like xAI’s Grok and Google’s Gemini . However, these tools often lacked the same level of detail and artistic refinement as OpenAI’s model. Now, with the rollout extending to free users, everyone can experience the magic of Ghibli-style AI transformations. How to Create Ghibli-Style AI Images with ChatGPT If you want to turn your photos into Ghibli-inspired masterpieces, follow these simple steps: Visit ChatGPT – Open the ChatGPT website or...

Quiz tells you what type of wife you want

What Type of Wife are You Looking For? Attend this quiz and know your wife expections Quiz reveals type of wife you expect, lets answer carefully... Personality Questions: 1. What type of personality are you looking for in a wife? Quiet and reserved Outgoing and social Intelligent and witty 2. What type of sense of humor are you looking for in a wife? Dry and sarcastic Witty and clever Playful and silly 3. What type of interests are you looking for in a wife? Intellectual and educational Creative and artistic Athletic and outdoorsy Values Questions: 4. What type of family values are you looking for in a wife? Traditional and conservative Open-minded and progressive Balanced and equal 5. What type of political views...