1 2
1 3
2 4
2 5
3 6
3 7
위와 같은 입력으로 인해 아래의 이진트리가 생성
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
int ch[101];
queue<int> Q;
vector<int> graph[101];
int main() {
freopen("input.txt", "rt", stdin);
for(int i=1; i<=6; i++) {
int a, b;
cin >> a >> b;
graph[a].push_back(b);
graph[b].push_back(a);
}
Q.push(1);
ch[1] = 1;
while(!Q.empty()) {
int x = Q.front();
cout << x << " ";
Q.pop();
for(int i=0; i<graph[x].size(); i++) {
if(ch[graph[x][i]] == 0) {
ch[graph[x][i]] = 1;
Q.push(graph[x][i]);
}
}
}
return 0;
}
BFS는 queue를 사용하여 풀이하는 것이 일반적이다.
ex)
1 2
1 3
2 4
2 5
3 6
3 7