예시소스코드

#include <iostream> #include <vector> #include <queue> #include <list> using namespace std; struct Vertex { }; vector<Vertex> vertices; vector < vector<int> > adjancent; vector<bool> discovered; // 발견 여부 void CreateGraph() { vertices.resize(6); adjancent = vector < vector<int>>(6); adjancent[0] = { 1,3 }; adjancent[1] = { 0,2 ,3}; adjancent[3] = { 4 }; adjancent[5] = { 4 }; } void Bfs(int here) { queue<int> q; q.push(here); discovered[here] = true; // q [ 0 ] // 1 q [ 3 2 ] while (q.empty() == false) { here = q.front(); // here = 0 // here = 1 q.pop(); cout << "Visited: " << here << endl; for (int there : adjancent[here]) { // 1, 3 if (discovered[there]) continue; // 미발견 상태 q.push(there); discovered[there] = true; } } } int main() { CreateGraph(); discovered = vector<bool>(6, false); Bfs(0); }