-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDFS.cpp
65 lines (60 loc) · 1.44 KB
/
DFS.cpp
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
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
class Graph {
public:
Graph(int V);
void addEdge(int u, int v);
void DFS(int start);
private:
int V;
vector<vector<int>> adj;
};
Graph::Graph(int V) {
this->V = V;
adj.resize(V);
}
void Graph::addEdge(int u, int v) {
adj[u].push_back(v);
adj[v].push_back(u);
}
void Graph::DFS(int start) {
vector<bool> visited(V, false);
stack<int> s;
s.push(start);
while (!s.empty()) {
int node = s.top();
s.pop();
if (!visited[node]) {
visited[node] = true;
cout << node << " ";
for (int neighbor : adj[node]) {
if (!visited[neighbor]) {
s.push(neighbor);
}
}
}
}
}
int main() {
int V, E;
cout << "Εισάγετε τον αριθμό των κόμβων (V): ";
cin >> V;
Graph g(V);
cout << "Εισάγετε τον αριθμό των ακμών (E): ";
cin >> E;
cout << "Εισάγετε τις ακμές (u v): " << endl;
for (int i = 0; i < E; i++) {
int u, v;
cin >> u >> v;
g.addEdge(u, v);
}
int start;
cout << "Εισάγετε τον κόμβο εκκίνησης για τον DFS: ";
cin >> start;
cout << "Αποτελέσματα DFS από τον κόμβο " << start << ": ";
g.DFS(start);
cout << endl;
return 0;
}