https://www.acmicpc.net/problem/1260
1260번: DFS와 BFS
첫째 줄에 정점의 개수 N(1 ≤ N ≤ 1,000), 간선의 개수 M(1 ≤ M ≤ 10,000), 탐색을 시작할 정점의 번호 V가 주어진다. 다음 M개의 줄에는 간선이 연결하는 두 정점의 번호가 주어진다. 어떤 두 정점 사
www.acmicpc.net
#include <iostream>
#include <vector>
#include <queue>
#include <stdio.h>
#include <algorithm>
using namespace std;
vector<vector<int>> nodes(1001);
bool visit[1001] = { false };
void dfs(int n) {
printf("%d ", n);
for (int i : nodes[n]) {
if (!visit[i]) {
visit[i] = true;
dfs(i);
}
}
}
int main() {
int N, M, start; cin >> N >> M >> start;
for (int i = 0; i < M; i++) {
int a, b; cin >> a >> b;
nodes[a].push_back(b);
nodes[b].push_back(a);
}
for (int i = 1; i <= N; i++) {
sort(nodes[i].begin(), nodes[i].end());
}
visit[start] = true;
dfs(start);
printf("\n");
bool bvisit[1001] = { false };
bvisit[start] = true;
queue<int> q;
q.push(start);
while (!q.empty()) { //bfs
int n = q.front();
printf("%d ", n);
q.pop();
for (int i : nodes[n]) {
if (!bvisit[i]) {
bvisit[i] = true;
q.push(i);
}
}
}
return 0;
}'전공공부 > 코딩테스트' 카테고리의 다른 글
| (c++) 백준 "1780) 종이의 개수" (0) | 2022.06.07 |
|---|---|
| (c++) 백준 "1541) 잃어버린 괄호" (0) | 2022.06.07 |
| (c++) 백준 "11727) 2xn 타일링2" (0) | 2022.06.07 |
| (c++) 백준 "9461) 파도반 수열" (0) | 2022.06.06 |
| (c++) 백준 "9095) 1,2,3 더하기 (0) | 2022.06.06 |