#include <iostream>
#include <vector>
#include <stack>
using namespace std;
#define NODE_COUNT 8
#define EDGE_COUNT 18
//stack에 들어가면 방문한 것으로 판단
//해당 위치를 true로 해준다.
void DFS(int start, vector<int> graph[], int check[])
{
cout << "\n\nresult >> " << ' ';
stack<int> s;
s.push(start);
check[start]++;
cout << start << " ";
while (!s.empty()) {
int current = s.top();
s.pop();
for (int i = 0; i < graph[current].size(); i++) {
int next = graph[current][i];
if (!check[next]) {
cout << next << " ";
check[next]++;
s.push(current);//current로 다시 push 해야함.
s.push(next);
break;//너비가 아니라 깊이 우선이라
}
}
}
}
int main()
{
int n = NODE_COUNT, m = EDGE_COUNT, start =1; // 노드 개수 , 간선 개수
vector<int>graph[NODE_COUNT + 1];
int check[NODE_COUNT + 1] = { 0, };
for (int i = 0; i < m; i++) {
int u, v;
cin >> u >> v;
graph[u].push_back(v);
graph[v].push_back(u);
}
//나중에 하나의 정점에서 다음 탐색 시 node 값 순차적으로
//접근하고 싶으면 graph sort 하면 됨
DFS(start, graph, check);
return 0;
}
1 2
1 3
1 8
2 1
2 7
3 1
3 4
3 5
4 3
4 5
5 3
5 4
6 7
7 2
7 6
7 8
8 1
8 7
'C > Data Structure' 카테고리의 다른 글
BFS 구현 (0) | 2023.10.12 |
---|---|
Count Sort(계수 정렬) (0) | 2021.08.09 |
Quick Sort(퀵 정렬) (0) | 2021.08.04 |
Insertion Sort(삽입 정렬) (0) | 2021.08.02 |
Selection Sort(선택 정렬) (0) | 2021.08.02 |