< DFS >
- 다차원 배열에서 각 칸을 방문하는 경우 깊이를 우선으로!
- 스택을 주로 사용한다
- 재귀로도 가능
#include <stdio.h>
#include <vector>
using namespace std;
const int MAX = 100;
int n, m;
vector <int> myGraph[MAX];
bool visited[MAX];
void DFS(int x){
visited[x] = true;
printf("%d ", x);
for(int i = 0; i < myGraph[x].size(); i++){
int y = myGraph[x][i];
if(visited[y] == false){
DFS(y);
}
}
}
int main() {
scanf("%d %d", &n, &m);
for(int i = 0; i<m; i++){
int a, b;
scanf("%d %d", &a, &b);
myGraph[a].push_back(b);
myGraph[b].push_back(a);
}
DFS(1);
return 0;
}
출력 = 1 2 3 7 4 5 6 8 9
< 무방향 그래프에서 사이클 찾기 >
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> node[10005];
int visited[10005] = {0};
vector<int> cycle;
int findNode;
int N;
void solve(int curNode, int parentNode)
{
cout << "curNode : " << curNode << ", parentNode : " << parentNode << "\n";
if(visited[curNode] == 1) {
findNode = curNode;
cycle.push_back(curNode);
cout << "find : " << findNode << "\n";
return;
}
visited[curNode] = 1;
for(int i = 0; i < node[curNode].size(); i++) {
int nextNode = node[curNode][i];
cout << "curNode : " << curNode << ", nextNode : " << nextNode << "\n";
if(nextNode == parentNode)
continue;
solve(nextNode, curNode);
if (findNode == -1)
{
return;
}
if(findNode == curNode) {
findNode = -1;
return;
}
if (findNode >= 1)
{
cycle.push_back(curNode);
return;
}
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> N;
for (int i = 0; i < N; i++)
{
int a, b;
cin >> a >> b;
node[a].push_back(b);
node[b].push_back(a);
}
for(int i = 1; i <= N; i++) {
cout << i << ": ";
for(int j = 0; j < node[i].size(); j++) {
cout << node[i][j] << ", ";
}
cout << "\n";
}
cout << "//////////\n";
findNode = 0;
solve(1, 1);
sort(cycle.begin(), cycle.end());
cout << "사이클 길이 : " << cycle.size() << "\n";
cout << "사이클 원소 : \n";
for (int i = 0; i < cycle.size(); i++)
{
cout << cycle[i] << " ";
}
return 0;
}
5
5 2
2 4
4 3
3 1
1 2
1: 3, 2,
2: 5, 4, 1,
3: 4, 1,
4: 2, 3,
5: 2,
curNode : 1, parentNode : 1
curNode : 1, nextNode : 3
curNode : 3, parentNode : 1
curNode : 3, nextNode : 4
curNode : 4, parentNode : 3
curNode : 4, nextNode : 2
curNode : 2, parentNode : 4
curNode : 2, nextNode : 5
curNode : 5, parentNode : 2
curNode : 5, nextNode : 2
curNode : 2, nextNode : 4
curNode : 2, nextNode : 1
curNode : 1, parentNode : 2
find : 1
사이클 길이 : 4
사이클 원소 :
1 2 3 4