#include <algorithm>
#include <iostream>
#include <limits.h>
#include <vector>
#include <stack>
#include <queue>
using namespace std;
vector<int> graph[1001];
int N, M, V;
void dfs(int vertex)
{
static bool isVisited[1001] = { false };
isVisited[vertex] = true;
cout << vertex << ' ';
for (int next : graph[vertex])
{
if (isVisited[next] == false)
{
dffs(next);
}
}
}
void bfs()
{
// 1. 방문 여부를 저장해야 한다.
bool isVisited[1001] = { false };
// 2. DFS에 사용할 스택을 만든다.
queue<int> qu; // 스택에는 앞으로 방문할 정점이 저장된다.
qu.push(V); // 첫 번째로 방문할 정점
isVisited[V] = true;
// 3. 더이상 방문할 정점이 없을 때까지 방문한다.
while (false == qu.empty()) // 큐가 비어있다면 모든 정점을 방문한 것이다.
{
// 3-1. 정점을 방문한다.
int node = qu.front();
qu.pop();
cout << node << " ";
// 3-2. 다음으로 방문할 정점을 찾는다.
for (int nextNode : graph[node])
{
if (false == isVisited[nextNode])
{
qu.push(nextNode);
isVisited[nextNode] = true;
}
}
}
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
// 1. 그래프 구성
cin >> N >> M >> V;
for (int i = 0; i < M; ++i)
{
int start, end;
cin >> start >> end;
graph[end].push_back(start);
graph[start].push_back(end);
}
// 2. 작은 정점부터 방문 시키기 위해 정렬
for (int i = 1; i <= N; ++i)
{
sort(graph[i].begin(), graph[i].end());
}
//3. DFS
dfs(V);
cout << "\n";
//4. BFS
bfs();
}
dfs 는 스택보다 제귀함수로 표현하는것이 일반적이다.