깊이 우선 탐색(DFS)은 그래프에서 깊은 부분을 먼저 탐색하는 알고리즘이다.
탐색 도중 더 방문할 정점이 존재하지 않으면 뒤로 돌아가서 다른 경로를 찾아간다.

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int number = 5;
int check[5];
vector<int> a[6];
void dfs(int x) {
if (check[x])
return;
check[x] = true;
cout << x << " ";
for (int i = 0; i < a[x].size(); i++) {
int y = a[x][i];
dfs(y);
}
}
int main() {
// 0과 1을 연결
a[0].push_back(1);
a[1].push_back(0);
// 0과 2를 연결
a[0].push_back(2);
a[2].push_back(0);
// 0과 4을 연결
a[0].push_back(4);
a[4].push_back(0);
// 1과 2를 연결
a[1].push_back(2);
a[2].push_back(1);
// 2와 3을 연결
a[2].push_back(3);
a[3].push_back(2);
// 3과 4를 연결
a[3].push_back(4);
a[4].push_back(3);
// 2와 4를 연결
a[2].push_back(4);
a[4].push_back(2);
dfs(0);
return 0;
}