티스토리 뷰
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
vector<int> edge[10];
bool mark[10];
void bfs(int n) {
queue<int> q;
q.push(n);
mark[n] = true;
while(!q.empty()) {
int v = q.front();
cout << v << ' ';
q.pop(); // 첫 원소 pop
// bfs : 현재 정점에 연결된 모든 정점 q.push (방문 안한)
for(int x : edge[v]) {
if(!mark[x]) {
q.push(x);
mark[x] = true;
}
}
}
}
int main() {
int v, e;
cin >> v >> e;
for(int i = 0; i < e; i++) {
int f, t;
cin >> f >> t;
edge[f].push_back(t);
edge[t].push_back(f);
}
bfs(1);
}
현재 정점에 연결된 모든 정점을 방문해야 되기 때문에 DFS와 다르게 queue를 쓴다 (first in first out)
'알고리즘' 카테고리의 다른 글
| c++) Floyd Warshall (0) | 2021.12.28 |
|---|---|
| bfs 탐색 깊이 기록하기 (0) | 2021.07.19 |
| Recursion (재귀) (0) | 2021.07.15 |
| DFS를 이용한 조합 만들기 (0) | 2021.07.12 |
| DFS (0) | 2021.03.16 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- permutation
- CSS
- BFS
- Stack
- db
- two pointer
- C++
- DP
- 자료구조
- binary search
- floyd warshall
- 조합
- back tracking
- 이분탐색
- graph
- recursion
- C
- Implementation
- MVC
- Brute Force
- Spring
- Dijkstra
- dfs
- priority queue
- Python
- Tree
- Unity
- greedy
- Kruskal
- 재귀
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | 5 | 6 | 7 |
| 8 | 9 | 10 | 11 | 12 | 13 | 14 |
| 15 | 16 | 17 | 18 | 19 | 20 | 21 |
| 22 | 23 | 24 | 25 | 26 | 27 | 28 |
글 보관함
