#include <iostream>
#include <vector>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int MAX = 1001;
int n, m, v;
vector<pair<int, int>> dfsway;
queue<int> bfsway;
int visited[MAX];
bool cmp(pair<int, int> p1, pair<int, int> p2) {
if (p1.first == p2.first)
return p1.second < p2.second;
else
return p1.first < p2.first;
}
void dfs(int j) {
visited[j] = 1;
cout << j << " ";
for (int i = 0; i < dfsway.size(); i++) {
if ((dfsway[i].first == j) && visited[dfsway[i].second] == -1)
dfs(dfsway[i].second);
}
}
void bfs(int j) {
visited[j] = 1;
bfsway.push(j);
while (!bfsway.empty()) {
int start = bfsway.front();
cout << start << " ";
bfsway.pop();
for (int i = 0; i < dfsway.size(); i++) {
if ((dfsway[i].first == start) && visited[dfsway[i].second] == -1) {
bfsway.push(dfsway[i].second);
visited[dfsway[i].second] = 1;
}
}
}
}
int main(void) {
cin >> n >> m >> v;
memset(visited, -1, sizeof(visited));
for (int i = 0; i < m; i++) {
int start, end;
cin >> start >> end;
dfsway.push_back(make_pair(start, end));
dfsway.push_back(make_pair(end, start));
}
sort(dfsway.begin(), dfsway.end(), cmp);
dfs(v);
cout << endl;
memset(visited, -1, sizeof(visited));
bfs(v);
return 0;
}
'백준 알고리즘 > DFS' 카테고리의 다른 글
백준 미세먼지 안녕 C++ (0) | 2019.10.15 |
---|---|
백준 15683번 C++ (0) | 2019.09.19 |
백준 12100번 C++ (0) | 2019.09.19 |
백준 2468번 C++ (0) | 2019.02.25 |
백준 2667번 C++ (0) | 2019.02.25 |