-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdfs.cpp
More file actions
58 lines (47 loc) · 1.33 KB
/
dfs.cpp
File metadata and controls
58 lines (47 loc) · 1.33 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
#include <iostream>
using namespace std;
void dfs(int **graph, int start, int n) {
bool *visited = new bool[n]{false}; // Dynamic allocation for visited array
int *stack = new int[n]; // Dynamic allocation for stack
int top = -1;
stack[++top] = start;
visited[start] = true;
while (top >= 0) {
int node = stack[top--];
cout << node << " ";
for (int i = 0; i < n; i++) {
if (graph[node][i] == 1 && !visited[i]) {
stack[++top] = i;
visited[i] = true;
}
}
}
// Free dynamically allocated memory
delete[] visited;
delete[] stack;
}
int main() {
int n, start;
cout << "Enter number of nodes: ";
cin >> n;
// Dynamically allocate the adjacency matrix
int **graph = new int*[n];
for (int i = 0; i < n; i++) {
graph[i] = new int[n]();
}
cout << "Enter the adjacency matrix (0 or 1 for each pair of nodes):" << endl;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> graph[i][j];
}
}
cout << "Enter the starting node for DFS: ";
cin >> start;
dfs(graph, start, n);
// Free dynamically allocated memory for the graph
for (int i = 0; i < n; i++) {
delete[] graph[i];
}
delete[] graph;
return 0;
}