Notice
Recent Posts
Recent Comments
Link
Little Jay
[C++] 백준 1260번 - DFS와 BFS 본문
기본적인 그래프문제
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <vector>
#include <queue>
#include <iostream>
using namespace std;
vector<int> a[1001];
bool check[1001];
void dfs(int node) {
check[node] = true;
printf("%d ", node);
for (int i = 0; i < a[node].size(); i++) {
int next = a[node][i];
if (check[next] == false) {
dfs(next);
}
}
}
void bfs(int start) {
queue<int> q;
memset(check, false, sizeof(check));
check[start] = true;
q.push(start);
while (!q.empty()) {
int node = q.front();
q.pop();
printf("%d ", node);
for (int i = 0; i < a[node].size(); i++) {
int next = a[node][i];
if (check[next] == false) {
check[next] = true;
q.push(next);
}
}
}
}
int main() {
int n, m, start;
cin >> n >> m >> start;
for (int i = 0; i < m; i++) {
int u, v;
cin >> u >> v;
a[u].push_back(v);
a[v].push_back(u);
}
for (int i = 1; i <= n; i++) {
sort(a[i].begin(), a[i].end());
}
dfs(start);
puts("");
bfs(start);
puts("");
return 0;
}'알고리즘 > BOJ' 카테고리의 다른 글
| [C++] 백준 2606번 - 바이러스 (0) | 2021.08.19 |
|---|---|
| [C++] 백준 11724번 - 연결 요소의 개수 (0) | 2021.08.19 |
| [C++] 백준 1931번 - 회의실 배정 (0) | 2021.08.18 |
| [C++] 백준 1406번 - 에디터 (0) | 2021.08.18 |
| [C++] 백준 4889번 - 안정적인 문자 (0) | 2021.08.17 |
Comments