-> 스택을 이용하여 그래프 순회
#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){
// x노드 부터 시작하는 dfs 하여 그 순서를 출력하는 함수
// visited 배열에 방문 기록
visited[x] = true;
printf("%d ", x); // 방문한 노드x를 출력
for(int i = 0; i < myGraph[x].size(); i++){
int y = myGraph[x][i];
if(visited[y] == false){
DFS(y);
}
}
}
int main() {
//노드 수 9 간선 수 12
//간선
//1 2
//1 3
//2 3
//2 4
//2 6
//3 7
//4 5
//4 7
//4 8
//5 6
//7 8
//8 9
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 <stdio.h>
#include <vector>
#include <queue> // STL 사용!
using namespace std;
int n, m;
const int MAX = 100;
vector <int> myGraph[MAX];
void BFS(){ // 너비 우선 탐색은 DFS와 다르게 재귀x
// 1. 시작점을 큐에 삽입
// 2. 시작점을 색칠
// 3. BFS 시작
// 4. 큐에서 하나를 뺀다 / 이곳이 현재 위치
// 5. 인접한 모든 정점 방문 여부를 체크하고
// 미방문 노드라면 방문 상태로 바꾸고 큐에 삽입
// 6. 모두 완료했다면 다시 3으로 돌아간다
bool check[MAX] = {0,};
// check[x] true 이면 노드 x 색칠
queue <int> Queue;
Queue.push(1);
check[1] = true;
while(!Queue.empty()){ // 비어있으면 종료
int current = Queue.front();
Queue.pop();
printf("%d ", current);
for(int i = 0; i < myGraph[current].size(); i++){
int next = myGraph[current][i];
if(check[next] == false){
check[next] = true;
Queue.push(next);
}
}
}
}
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);
}
BFS();
return 0;
}