In the world of computer science and programming, graphs are a fundamental data structure used to represent a collection of interconnected nodes. They are versatile and have wide-ranging applications in solving various problems.
A graph consists of two main components:
- Nodes: Also known as vertices, these are the entities that make up a graph. Each node can hold some data or value.
- Edges: These are connections or relationships between nodes. Edges can be either directed or undirected, indicating the directionality of the relationship.
Graphs can be used to model real-world scenarios such as social networks, transportation systems, computer networks, and more. They are particularly useful in scenarios where relationships and connections between entities need to be represented and analyzed.
There are several common operations performed on graphs, including:
- Adding Nodes and Edges: Adding new nodes and creating relationships between them.
- Removing Nodes and Edges: Deleting nodes and removing relationships between nodes.
- Traversal: Visiting and exploring nodes and edges in a graph.
- Searching: Finding nodes or paths within a graph.
Here is an example of performing a Depth-First Search (DFS) on a graph in C++:
TEXT/X-C++SRC
1#include <iostream>
2#include <vector>
3
4void dfs(int node, vector<vector<int>>& graph, vector<bool>& visited) {
5 visited[node] = true;
6 cout << "Visiting node " << node << endl;
7
8 for (int neighbor : graph[node]) {
9 if (!visited[neighbor]) {
10 dfs(neighbor, graph, visited);
11 }
12 }
13}
14
15int main() {
16 // Create the graph
17 vector<vector<int>> graph(5);
18
19 graph[0] = {1, 2};
20 graph[1] = {0, 2, 3};
21 graph[2] = {0, 1, 4};
22 graph[3] = {1};
23 graph[4] = {2};
24
25 // Initialize visited array
26 vector<bool> visited(5, false);
27
28 // Perform Depth-First Search
29 dfs(0, graph, visited);
30
31 return 0;
32}
xxxxxxxxxx
32
}
void dfs(int node, vector<vector<int>>& graph, vector<bool>& visited) {
visited[node] = true;
cout << "Visiting node " << node << endl;
for (int neighbor : graph[node]) {
if (!visited[neighbor]) {
dfs(neighbor, graph, visited);
}
}
}
int main() {
// Create the graph
vector<vector<int>> graph(5);
graph[0] = {1, 2};
graph[1] = {0, 2, 3};
graph[2] = {0, 1, 4};
graph[3] = {1};
graph[4] = {2};
// Initialize visited array
vector<bool> visited(5, false);
// Perform Depth-First Search
dfs(0, graph, visited);
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment