-
Notifications
You must be signed in to change notification settings - Fork 0
/
tbbfs.cpp
92 lines (80 loc) · 1.73 KB
/
tbbfs.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
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
//http://www.spoj.com/problems/TDBFS/
#include<bits/stdc++.h>
#define dout if(debugg) cout<<" "
using namespace std;
int debugg = 1;
class Node{
public:
vector<int> adj;
int visited;
Node(){
clear();
}
void clear(){
visited = 0;
adj.clear();
}
};
void dfs_rec(vector<Node> &node,int a){
cout<<a<<" ";
for(auto i : node[a].adj){
if(node[i].visited==0){
node[i].visited=1;
dfs_rec(node,i);
}
}
}
void dfs(vector<Node> &node,int a){
for(auto &i : node){
i.visited=0;
}
node[a].visited=1;
dfs_rec(node,a);
cout<<endl;
}
void bfs(vector<Node> &node,int a){
for(auto &i : node)
i.visited=0;
queue<int> q;
q.push(a);
node[a].visited=1;
while(!q.empty()){
int temp = q.front();
for(auto i : node[temp].adj){
if(node[i].visited==0){
node[i].visited=1;
q.push(i);
}
}
q.pop();
cout<<temp<<" ";
}
cout<<endl;
}
int main(){
int t,temp;
cin>>t;
for(int x=1; x<=t; x++){
int n;
cin>>n;
vector<Node> node(n+1);
for(int i=1; i<=n; i++){//insert adj nodes
int m,faltu;
cin>>faltu>>m;
while(m--){
cin>>temp;
node[i].adj.push_back(temp);
}
}
cout<<"graph "<<x<<endl;
while(true){
int a,type;
cin>>a>>type;
if(a==0)break;
if(type)
bfs(node,a);
else
dfs(node,a);
}
}
}