본문 바로가기

C++

[C++] BFS(너비우선탐색)알고리즘 코드 구현

#include<vector>
#include<iostream>
#include<algorithm>
#define _CRT_SECURE_NO_WARNINGS
using namespace std;

void bfs(vector<int>graph[], int start_node) {
	vector<int> visited;
	vector<int> need_visit;

	need_visit.push_back(start_node);
	
	while (!need_visit.empty()) {
		int node = need_visit.front();
		need_visit.erase(need_visit.begin());
		if (find(visited.begin(), visited.end(), node) == visited.end()) {
			visited.push_back(node);
			for (int i = 0; i < graph[node].size(); i++)
				need_visit.push_back(graph[node][i]);
		}
	} 

	for (int elem : visited)
		cout << elem << " ";

	return;
}

int main()
{
	vector<int> graph[11];

	graph[1] = { 2,3 };
	graph[2] = { 1,4 };
	graph[3] = { 1,5,6,7 };
	graph[4] = { 2,8,9 };
	graph[5] = { 3 };
	graph[6] = { 3 };
	graph[7] = { 3,10 };
	graph[8] = { 4 };
	graph[9] = { 4 };
	graph[10] = { 7 };

	bfs(graph, 1);
}