-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdfs.cpp
More file actions
77 lines (64 loc) · 2.2 KB
/
dfs.cpp
File metadata and controls
77 lines (64 loc) · 2.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include <bits/stdc++.h>
using namespace std;
#define MAX 100 // Define the maximum number of nodes
int st[MAX]; // Stack for DFS
int top = -1; // Top of the stack
int adj[MAX][MAX]; // Adjacency matrix for the graph
bool visited[MAX]; // Array to keep track of visited nodes
// Function to push an element onto the stack
void push(int data) {
st[++top] = data;
}
// Function to pop an element from the stack
int pop() {
return st[top--];
}
// Function to check if the stack is empty
bool isEmpty() {
return top == -1;
}
// Function to perform DFS traversal
void dfs(int nodes, int start) {
push(start); // Push the starting node onto the stack
while (!isEmpty()) { // While the stack is not empty
int u = pop(); // Pop a node from the stack
if (!visited[u]) { // If the node has not been visited
visited[u] = true; // Mark the node as visited
cout << u << " "; // Print the node
for (int v = nodes; v >= 1; v--) { // Visit all adjacent nodes
if (adj[u][v] && !visited[v]) { // If there is an edge and the node is not visited
push(v); // Push the adjacent node onto the stack
}
}
}
}
}
int main() {
// Define the number of nodes and edges
int nodes = 5;
int edges = 4;
// Initialize adjacency matrix with 0
for (int i = 0; i < MAX; i++) {
for (int j = 0; j < MAX; j++) {
adj[i][j] = 0;
}
}
// Initialize visited array with false
for (int i = 0; i < MAX; i++) {
visited[i] = false;
}
// Example edges of the graph (undirected)
// Edge list: (1-2), (1-3), (2-4), (3-5)
int edgeList[4][2] = {{1, 2}, {1, 3}, {2, 4}, {3, 5}};
// Build the adjacency matrix from the edge list
for (int i = 0; i < edges; i++) {
int u = edgeList[i][0];
int v = edgeList[i][1];
adj[u][v] = 1;
adj[v][u] = 1; // Since the graph is undirected
}
// Output the DFS traversal starting from node 1
cout << "DFS traversal starting from node 1: ";
dfs(nodes, 1); // Start DFS from node 1
return 0;
}