![]() |
A graph is a type of non-linear data structure that has two types of components “Vertices” (nodes) and “edges”. It contains a set of vertices (V) and a set of edges (E). Two nodes of the graph are connected by an edge. A graph is denoted by G(V, E). ![]() Example of a Graph Ways to represent a Graph:There are two major ways of representing a Graph in C++:
The other way of representing the graph may include Incidence Matrix and Incidence List. The way to represent the graph we use is based on our requirements. Adjacency Matrix:The graph is represented in the form of a Matrix. It is a V * V matrix, where V represents the number of vertices present in the graph. Let us take a matrix as adj[][]. If there is any value in the cell adj[i][j], it represents that there is an edge from i to j. The adjacency matrix for an undirected graph is always symmetric. It can be used to represent the weighted graph and unweighted graph. In an unweighted graph adj[i][j] = 1 but in a weighted graph adj[i][j] is equal to the weight of the edge. ![]() Example of an adjacency matrix Adjacency List:It is also a common method of representing the graph. Let the list be array[]. An entry array[i] represents the list of vertices that are adjacent to the ith vertex. It can also be used to represent a weighted graph. When it is being used to represent a weighted graph then the weights of edges can be represented as lists of pairs. ![]() Example of adjacency list Generate a random Graph using an Adjacency Matrix:Follow the below steps to implement:
Below is the implementation of the above approach.
Output Random graph generation: The graph has 8 vertices and has 18 edges. The generated random graph is: 1-> { 5 4 2 } 2-> { 4 8 6 3 1 5 } 3-> { 5 4 7 2 } 4-> { 2 3 7 1 8 5 } 5-> { 3 1 7 4 2 8 } 6-> { 2 8 7 } 7-> { 4 3 5 6 } 8-> { 2 6 4 5 } Time Complexity: O(E2 + E*V) where E is the number of edges and V is the number of vertices Related Articles: |
Reffered: https://www.geeksforgeeks.org
Graph |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 12 |