#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> graph[10];
bool visited[10] = {false};
// 그래프 만들기
graph[1].push_back(2);
graph[1].push_back(3);
graph[2].push_back(4);
graph[2].push_back(5);
vector<int> st; // 스택 역할
st.push_back(1); // 시작 노드
while (!st.empty()) {
int x = st.back(); // top
st.pop_back(); // pop
if (visited[x]) continue;
visited[x] = true;
cout << x << " ";
// 뒤에서부터 push 해야 DFS 재귀 순서와 같아짐
for (int i = graph[x].size() - 1; i >= 0; i--) {
int next = graph[x][i];
if (!visited[next]) {
st.push_back(next);
}
}
}
}
To embed this project on your website, copy the following code and paste it into your website's HTML: