Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
31 |
Tags
- Set
- priority_queue
- 문자열
- vector
- 유클리드호제법
- N과M
- 다이나믹프로그래밍
- 에라토스테네스의 체
- 배열
- 우선순위큐
- 분할정복
- Sort
- stoi
- 알고리즘
- 백트래킹
- 백준
- 오블완
- int
- BFS
- 프로그래머스
- DP
- 이분탐색
- 최소공배수
- 티스토리챌린지
- DFS
- 그래프
- C++
- 깊이우선탐색
- map
- 정렬
Archives
- Today
- Total
안녕 세상아,
[백준/c++] 1260 DFS와 BFS 본문
https://www.acmicpc.net/problem/1260
BFS와 DFS의 기본적인 문제이다. 템플릿으로 사용해도 될듯..
값을 입력할 때 양방향 간선으로 고려해야한다. 또한, 방문할 수 있는 정점이 여러 개인 경우에는 정점 번호가 작은 것을 먼저 방문 한다는 조건을 생각해서 정렬한다.
#include <iostream>
#include <vector>
#include <queue>
#include <string>
#include <algorithm>
using namespace std;
int n, m, v;
bool isVisited[1001] = { false };
vector<int> graph[1001];
void reset() {
for (int i = 1; i <= n; i++) {
isVisited[i] = false;
}
}
void bfs(int start) {
queue<int> q;
q.push(start);
isVisited[start] = true;
while (!q.empty()) {
int x = q.front();
q.pop();
cout << x << " ";
for (int i = 0; i < graph[x].size(); i++) {
int y = graph[x][i];
if (!isVisited[y]) {
isVisited[y] = true;
q.push(y);
}
}
}
}
void dfs(int x) {
isVisited[x] = true;
cout << x << " ";
for (int i = 0; i < graph[x].size(); i++) {
int y = graph[x][i];
if (!isVisited[y]) {
dfs(y);
}
}
}
int main() {
cin >> n >> m >> v;
for (int i = 0; i < m; i++) {
int a, b;
cin >> a >> b;
graph[a].push_back(b);
graph[b].push_back(a);
}
for (int i = 1; i <= n; i++) {
sort(graph[i].begin(), graph[i].end());
}
dfs(v);
cout << endl;
reset();
bfs(v);
}
'백준' 카테고리의 다른 글
[백준/c++] 1654 랜선 자르기 (0) | 2025.01.18 |
---|---|
[백준/c++] 2776 암기왕 (1) | 2025.01.13 |
[백준/c++] 1436 영화감독 (0) | 2025.01.08 |
[백준/c++] 10814 나이순 정렬 (1) | 2025.01.06 |
[백준/c++] 분수 찾기 (0) | 2025.01.02 |