https://www.acmicpc.net/problem/1260
#include <iostream>
#include <queue>
#include <vector>
#include <algorithm>
using namespace std;
int n, m, v;
queue<int> q;
vector<int> arr[1001];
int bfs_check[1001] = { 0, };
int dfs_check[1001] = { 0, };
void bfs() {
while (!q.empty()){
int now = q.front();
q.pop();
cout << now << " ";
for (int i = 0; i < arr[now].size(); i++) {
int next = arr[now][i];
if (bfs_check[next]) continue;
bfs_check[next] = 1;
q.push(next);
}
}
}
void dfs(int now) {
cout << now << " ";
for (int i = 0; i < arr[now].size(); i++) {
int next = arr[now][i];
if (dfs_check[next]) continue;
dfs_check[next] = 1;
dfs(next);
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n >> m >> v;
for (int i = 0; i < m; i++) {
int start, end;
cin >> start >> end;
arr[start].push_back(end);
arr[end].push_back(start);
}
for (int i = 0; i < n+1; i++) {
sort(arr[i].begin(), arr[i].end());
}
q.push(v);
bfs_check[v] = 1;
dfs_check[v] = 1;
dfs(v);
cout << "\n";
bfs();
return 0;
}
나가서 C++ 공부중이신가요?