https://www.acmicpc.net/problem/1260
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
#include <cstring>
using namespace std;
vector<int> a[1001];
bool check[1001];
void dfs(int start) {
check[start] = true;
cout << start << ' ';
for (int i = 0; i < a[start].size(); i++) {
if (!check[a[start][i]]) {
dfs(a[start][i]);
}
}
}
void bfs(int start) {
memset(check, false, sizeof(check));
queue<int> q;
q.push(start);
check[start] = true;
while (!q.empty()) {
int node = q.front();
cout << node << ' ';
q.pop();
for (int i = 0; i < a[node].size(); i++) {
if (!check[a[node][i]]) {
q.push(a[node][i]);
check[a[node][i]] = true;
}
}
}
}
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);
cout << '\n';
bfs(start);
return 0;
}
'algorithm > dfs,bfs' 카테고리의 다른 글
[프로그래머스] 단어 변환 (0) | 2020.08.25 |
---|---|
[백준/2667] 단지번호붙이기 (0) | 2020.04.06 |
[백준/2606] 바이러스 (0) | 2020.04.04 |
댓글