그래프 탐색 기법인 DFS와 BFS에 대해 알아보았다.
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
#define MAX 10
using namespace std;
int n,m,start;
bool visited[MAX]={0};
vector<int> graph[MAX];
void Input(){
cin>>n>>m>>start;
fill(visited, visited+n+1, false);
for(int i=0; i<m; i++){
int a,b;
cin>>a>>b;
graph[a].push_back(b);
graph[b].push_back(a);
}
for(int i=1; i<=n; i++){
sort(graph[i].begin(), graph[i].end());
}
}
void DFS(int cur){
visited[cur]=true;
cout<<cur<<" ";
for(int i=0; i<graph[cur].size(); i++){
int next=graph[cur][i];
if(!visited[next])
DFS(next);
}
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
Input();
DFS(start);
return 0;
}
#include <iostream>
#include <vector>
#include <queue>
#include <stack>
#include <algorithm>
#define MAX 10
using namespace std;
int n,m,start;
bool visited[MAX]={0};
vector<int> graph[MAX];
void Input(){
cin>>n>>m>>start;
fill(visited, visited+n+1, false);
for(int i=0; i<m; i++){
int a,b;
cin>>a>>b;
graph[a].push_back(b);
graph[b].push_back(a);
}
for(int i=1; i<=n; i++){
sort(graph[i].begin(), graph[i].end());
}
}
void DFS(int cur){
stack<int> s;
s.push(cur);
visited[cur]=true;
cout<<cur<<" ";
while(!s.empty()){
int current=s.top();
s.pop();
for(int i=0; i<graph[current].size(); i++){
int next=graph[current][i];
if(!visited[next]){
cout<<next<<" ";
visited[next]=true;
s.push(current);
s.push(next);
break;
}
}
}
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
Input();
DFS(start);
return 0;
}
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
#define MAX 10
using namespace std;
int n,m,start;
bool visited[MAX]={0};
vector<int> graph[MAX];
void Input(){
cin>>n>>m>>start;
fill(visited, visited+n+1, false);
for(int i=0; i<m; i++){
int a,b;
cin>>a>>b;
graph[a].push_back(b);
graph[b].push_back(a);
}
for(int i=1; i<=n; i++){
sort(graph[i].begin(), graph[i].end());
}
}
void BFS(int cur){
queue<int> q;
q.push(cur);
visited[cur]=true;
while(!q.empty()){
int tmp=q.front();
q.pop();
for(int i=0; graph[tmp].size(); i++){
if(!visited[tmp]){
q.push(graph[tmp][i]);
visited[tmp]=true;
}
}
}
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
Input();
BFS(start);
return 0;
}