-
Notifications
You must be signed in to change notification settings - Fork 0
/
SCTDL105.cpp
100 lines (90 loc) · 2.39 KB
/
SCTDL105.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
93
94
95
96
97
98
99
100
/**
* @file SCTDL101.cpp
* @author long ([email protected])
* @brief DFS non-directional
* @version 0.1
* @date 2023-04-09
*
* @copyright Copyright (c) 2023
*
*/
#include <iostream>
#include <vector>
#include <algorithm>
#include <stack>
using namespace std;
void Init_vertex_list(vector<vector<int> >* list, const int V);
void Transform_to_vertex_list(vector<vector<int> >* list, const int E);
void Sort_vertex_list(vector<vector<int> >* list, const int V);
void Display_vertex_list(vector<vector<int> >* list, const int V);
void DFS(vector<vector<int> >* list, const int V, int u);
int main() {
int t;
cin >> t;
while (t--) {
int V, E, u;
vector<vector<int> > list;
cin >> V >> E >> u;
Init_vertex_list(&list, V);
Transform_to_vertex_list(&list, E);
Sort_vertex_list(&list, V);
//Display_vertex_list(&list, V);
DFS(&list, V, u);
cout << endl;
list.clear();
}
}
void Init_vertex_list(vector<vector<int> >* list, const int V) {
vector<int> vertex_list;
for(int i = 0; i <= V; i++) {
list->push_back(vertex_list);
}
}
void Transform_to_vertex_list(vector<vector<int> >* list, const int E) {
int vx, vy;
for(int i = 0; i < E; i++) {
cin >> vx >> vy;
list->at(vx).push_back(vy);
//list->at(vy).push_back(vx);
}
}
void Sort_vertex_list(vector<vector<int> >* list, const int V) {
int i;
for( i=0; i <= V; i++) {
sort(list->at(i).begin(), list->at(i).end());
}
}
void Display_vertex_list(vector<vector<int> >* list, const int V) {
int i, j;
for( i=1; i <= V; i++) {
cout << i << ": ";
for( j = 0; j < list->at(i).size(); j++) {
cout << list->at(i).at(j) << " ";
}
cout << endl;
}
}
void DFS(vector<vector<int> >* list, const int V, int u) {
bool notVisited[V+1];
for(int i=0; i <= V; i++) {
notVisited[i] = true;
}
stack<int> st;
cout << u << " ";
notVisited[u] = false;
st.push(u);
while(!st.empty()) {
int s = st.top();
st.pop();
for(int i = 0; i < list->at(s).size(); i++) {
int v = list->at(s).at(i);
if(notVisited[v] == true) {
cout << v << " ";
notVisited[v] = false;
st.push(s);
st.push(v);
break;
}
}
}
}