승쨩개발공부
[BJ] 1260 - DFS와 BFS (그래프) 본문
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;
int n, m, k;
vector<int> v[1005];
bool vis[1005];
queue<int> q;
void bfs(int here)
{
vis[here] = true;
q.push(here);
while (q.size())
{
int front = q.front();
q.pop();
cout << front << ' ';
for (const int& i : v[front])
{
if (!vis[i])
{
q.push(i);
vis[i] = true;
}
}
}
}
void dfs(int here)
{
vis[here] = true;
cout << here << ' ';
for (const int& i : v[here])
{
if (!vis[i])
{
dfs(i);
}
}
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> n >> m >> k;
for (int i = 0; i < m; ++i)
{
int a, b;
cin >> a >> b;
v[a].push_back(b);
v[b].push_back(a);
}
for (int i = 1; i <= n; ++i)
{
if (v[i].size() > 1)
{
sort(v[i].begin(), v[i].end());
}
}
dfs(k);
fill(&vis[0], &vis[0] + 1005, 0);
cout << '\n';
bfs(k);
return 0;
}

예제 1 보기

DFS

dfs = 1,2,4,3
BFS

bfs 1,2,3,4
'CodingTestTraining > BaekJoon(Basic)' 카테고리의 다른 글
| [BJ] 6603 - 로또 (백트래킹) (0) | 2025.10.28 |
|---|---|
| [BJ] 1697 - 숨바꼭질 (BPS 1차원 최단거리 변형) (0) | 2025.10.28 |
| [BJ] 2568 - 안전 영역 (DFS 모든 경우의 수) (0) | 2025.10.28 |
| [BJ] 1629 - 곱샘 (재귀기초, 모듈러 성질, 귀납적사고) (0) | 2025.03.06 |
| [BJ] 1926 - 그림 (BFS) (0) | 2025.02.24 |