Table of contents | |
Introduction | |
Types of Graphs: | |
Graph Representation | |
Graph Traversals | |
Connectivity in Graphs | |
Sample Problems | |
Conclusion |
In computer science and data structures, a graph is a non-linear data structure that consists of a collection of nodes (vertices) connected by edges. Graphs are widely used to represent relationships and connections between objects in various applications such as social networks, road networks, and computer networks. This article aims to provide a beginner-friendly explanation of the basic properties of a graph and how to implement them using C++.
Adjacency Matrix: An adjacency matrix is a 2D array that represents a graph. The value at the intersection of row i and column j represents whether there is an edge between vertex i and vertex j.
Example:
#include <iostream>
#define MAX_SIZE 100
using namespace std;
class Graph {
int vertices;
int adjacencyMatrix[MAX_SIZE][MAX_SIZE];
public:
Graph(int V) {
vertices = V;
for (int i = 0; i < vertices; i++) {
for (int j = 0; j < vertices; j++) {
adjacencyMatrix[i][j] = 0;
}
}
}
void addEdge(int source, int destination) {
adjacencyMatrix[source][destination] = 1;
adjacencyMatrix[destination][source] = 1;
}
void display() {
for (int i = 0; i < vertices; i++) {
for (int j = 0; j < vertices; j++) {
cout << adjacencyMatrix[i][j] << " ";
}
cout << endl;
}
}
};
int main() {
Graph graph(4);
graph.addEdge(0, 1);
graph.addEdge(0, 2);
graph.addEdge(1, 2);
graph.addEdge(2, 3);
graph.display();
return 0;
}
Output:
0 1 1 0
1 0 1 0
1 1 0 1
0 0 1 0
Explanation:
Connected Graph: A connected graph is a graph in which there is a path between every pair of vertices.
Disconnected Graph: A disconnected graph consists of two or more connected components, where a connected component is a subgraph in which there is a path between every pair of vertices.
Now that you have a basic understanding of the properties of a graph, their representation, and common algorithms, you can further explore advanced concepts such as minimum spanning trees, topological sorting, and more.
In conclusion, understanding the basic properties of a graph is essential in the field of data structures and algorithms. Graphs allow us to represent relationships and connections between objects in a wide range of applications. In this article, we covered the types of graphs, graph representation using adjacency matrix, and basic graph algorithms such as DFS and BFS.
153 videos|115 docs|24 tests
|
|
Explore Courses for Software Development exam
|