[주의]
1. 에지 양방향 간선 처리해주기
2. 인접리스트 정렬하기
#include <iostream>
#include <queue>
#include <vector>
#include <algorithm>
#include <limits.h>
using namespace std;
static int N, M, V;
static vector<bool>visited;
static vector<vector<int>>alist;
static queue<int>q;
void DFS(int now) {
cout << now << " ";
for (int i = 0; i < alist[now].size(); i++) {
int next = alist[now][i];
if (visited[next] == 1)continue;
visited[next] = 1;
DFS(next);
}
}
void BFS(int start) {
std::fill(visited.begin(), visited.end(), false);
q.push(start);
visited[start] = 1;
while (!q.empty()) {
int now = q.front();
q.pop();
cout << now << " ";
for (int i = 0; i < alist[now].size(); i++) {
int next = alist[now][i];
if (visited[next] == 1)continue;
visited[next] = 1;
q.push(next);
}
}
}
int main() {
cin >> N >> M >> V;
alist.resize(N + 1);
visited.resize(N + 1);
for (int i = 0; i < M; i++) {
int from;
int to;
cin >> from >> to;
alist[from].push_back(to);
alist[to].push_back(from);
}
for (int i = 1; i <= N; i++) {
sort(alist[i].begin(), alist[i].end());
}
visited[V] = 1;
DFS(V);
cout << "\n";
BFS(V);
return 0;
}