-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdfs.cpp
More file actions
107 lines (92 loc) · 1.87 KB
/
dfs.cpp
File metadata and controls
107 lines (92 loc) · 1.87 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#include <bits/stdc++.h>
using namespace std;
typedef vector<vector<int>> GRAPH;
void add_directed_edge(GRAPH &graph, int from, int to)
{
graph[from].push_back(to);
}
void print_adjaceny_list(GRAPH &graph)
{
int nodes = graph.size();
for (int from = 0; from < nodes; ++from)
{
cout << "Node " << from << " has neighbors: ";
for (int to = 0; to < (int)graph[from].size(); ++to)
cout << graph[from][to] << " ";
cout << "\n";
}
}
void dfs(GRAPH &graph, int node, vector<bool> &visited)
{
visited[node] = true;
for (int neighbour : graph[node])
{
// Avoid cycling
if (!visited[neighbour])
{
cout << "\tWe can reach " << neighbour << "\n";
dfs(graph, neighbour, visited);
}
}
}
void reachability(GRAPH &graph)
{
int nodes = graph.size();
for (int i = 0; i < nodes; ++i)
{
vector<bool> visited(nodes); // RESET
cout << "Reachable set of node " << i << "\n";
dfs(graph, i, visited);
}
}
int main()
{
int nodes, edges;
cin >> nodes >> edges;
GRAPH graph(nodes); // observe: empty lists
for (int e = 0; e < edges; ++e)
{
int from, to;
cin >> from >> to;
add_directed_edge(graph, from, to);
}
reachability(graph);
return 0;
}
/*
7 9
2 0
0 1
1 4
4 3
3 1
1 0
0 3
5 6
6 6
Output
Reachable set of node 0
We can reach 1
We can reach 4
We can reach 3
Reachable set of node 1
We can reach 4
We can reach 3
We can reach 0
Reachable set of node 2
We can reach 0
We can reach 1
We can reach 4
We can reach 3
Reachable set of node 3
We can reach 1
We can reach 4
We can reach 0
Reachable set of node 4
We can reach 3
We can reach 1
We can reach 0
Reachable set of node 5
We can reach 6
Reachable set of node 6
*/