본문 바로가기

CodingTest Exam/[C++] Algorithm Study

69. 이진트리 넓이우선탐색(BFS) (it 취업을 위한 알고리즘 문제풀이 입문 (with C/C++) : 코딩테스트 대비) ★★☆☆☆

#include <stdio.h>
#include <queue>

using namespace std;

queue<int> q;
vector<int> map[8];

int main()
{
	int a, b, x = 1;
	for(int i = 1; i <= 6; i++)
	{
		scanf("%d %d", &a, &b);
		map[a].push_back(b);
	}
	
	q.push(1);
	
	while(!map[x].empty())
	{
		for(int i = 0; i < map[x].size(); i++)
		{
			q.push(map[x][i]);
		}
		
		while(!q.empty())
		{
			printf("%d ", q.front());
			q.pop();
		}
		x++;
	}
	
	return 0;
}

1. 7개 노드의 이진트리를 탐색하는 것이기 때문에 간선의 개수는 6개이다.

2. 현재노드를 a, 연결된 노드를 b에 입력받고 이를 인접 리스트 map에 저장한다.

3. queue는 FIFO(First In First Out) 이다. 이전에 공부했던 stack은 FILO 이었다면 queue는 그 반대이다.

먼저 들어간 원소가 먼저 나간다.