본문 바로가기
C++ 알고리즘/6. 검색 알고리즘

너비우선 탐색 (BFS) // 큐 사용해야됨

by Beijing_KingGod 2019. 9. 3.

#include <iostream>
#include <vector>
#include <queue>

using namespace std;
void bfs(int start,vector<vector <int>> temp) {
	queue <int> p;
	vector<bool> check(temp.size(), false);
	p.push(start);
	check[start] = true;
	for (int i = 0; i < temp[start].size(); i++) {
		if (temp[start][i] == 1) {
			p.push(i);
			check[i] = true;
		}
	}
	cout << p.front() << endl;
	p.pop();
	while (!p.empty()) {
		for (int i = 0; i < temp[p.front()].size(); i++) {
			if (temp[p.front()][i] == 1&&check[i]==false){
				p.push(i);
				check[i] = true;
			}
		}
		cout << p.front() << endl;
		p.pop();
	}
}
int main() {
	vector<vector<int>> temp = {
	{0,1,1,0,0,0,0},
	{1,0,1,1,1,0,0},
	{1,1,0,0,0,1,1},
	{0,1,0,0,1,0,0},
	{0,1,0,1,0,0,0},
	{0,0,1,0,0,0,1},
	{0,0,1,0,0,1,0}
	};
	for (int i = 0; i < temp.size(); i++) {
		for (int j = 0; j < temp[i].size(); j++) {
			cout << temp[i][j];
		}
		cout << endl;
	}
	bfs(0,temp);
	system("pause");
	return 0;
}
0110000
1011100
1100011
0100100
0101000
0010001
0010010
0
1
2
3
4
5
6

 

출처:https://blog.naver.com/PostView.nhn?blogId=ndb796&logNo=221230944971&categoryNo=128&parentCategoryNo=0&viewDate=¤tPage=7&postListTopCurrentPage=&from=postList&userTopListOpen=true&userTopListCount=5&userTopListManageOpen=false&userTopListCurrentPage=7

댓글