# 생각
dfs와 bfs 탐색 시 탐색되는 다음 index 값만 출력해주면 쉽게 해결가능하다
dfs와 bfs 탐색의 차이를 보여주는 기초적인 문제다
# 전체 코드
#include <bits/stdc++.h>
using namespace std;
int n, m, v;
int graph[1111][1111], vis[1111];
void dfs(int index)
{
cout << index << ' ';
vis[index] = true;
for (int nxt = 1; nxt <= n; nxt++)
{
if (graph[index][nxt] == 1 and vis[nxt] == false)
{
dfs(nxt);
}
}
}
void bfs(int st)
{
queue<int> q;
q.push(st);
vis[st] = true;
while (!q.empty())
{
auto cur = q.front();
q.pop();
for (int nxt = 1; nxt <= n; nxt++)
{
if (graph[cur][nxt] == 1 and vis[nxt] == false)
{
q.push(nxt);
vis[nxt] = true;
}
}
cout << cur << ' ';
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
cin >> n >> m >> v;
for (int i = 0; i < m; i++)
{
int from, to;
cin >> from >> to;
graph[from][to] = 1;
graph[to][from] = 1;
}
dfs(v);
cout << '\n';
fill(vis, vis + n + 1, 0);
bfs(v);
}
'Algorithm > BOJ' 카테고리의 다른 글
[BOJ] 2644_촌수계산 with cpp (0) | 2022.03.07 |
---|---|
[BOJ] 2606_바이러스 with cpp (0) | 2022.03.07 |
[BOJ] 1003_피보나치 함수 with cpp (0) | 2022.03.05 |
[BOJ] 12852_1로 만들기 2 with cpp (0) | 2022.03.04 |
[BOJ] 11659_구간 합 구하기 4 with cpp (0) | 2022.03.04 |