-
백준 1260번: DFS와 BFS문제해결 2023. 11. 30. 16:27
DFS와 BFS
너무 정직한 DFS, BFS 문제이다.
다만,단, 방문할 수 있는 정점이 여러 개인 경우에는 정점 번호가 작은 것을 먼저 방문하고,
이 부분 참고하여, DFS, BFS할 때 FIFO, LIFO에 맞춰 저렇게 sort 해준 뒤 push_back 해주면 끝.
#include <bits/stdc++.h> using namespace std; #define endl "\n" #define FOR(i, N) for (int i = 0; i < static_cast<int>(N); i++) #define FORL(e, S) for (auto& e : S) int N, M, V; vector<int> av[1000]; bool visited[1000]; void dfs() { memset(visited, 0, sizeof(bool) * 1000); vector<int> s = { V }; while (!s.empty()) { auto n = s.back(); s.pop_back(); if (visited[n]) continue; visited[n] = true; cout << n + 1 << " "; sort(av[n].begin(), av[n].end(), greater<int>()); FORL(e, av[n]) s.push_back(e); } cout << endl; } void bfs() { memset(visited, 0, sizeof(bool) * 1000); deque<int> q = { V }; while (!q.empty()) { auto n = q.front(); q.pop_front(); if (visited[n]) continue; visited[n] = true; cout << n + 1 << " "; sort(av[n].begin(), av[n].end()); FORL(e, av[n]) q.push_back(e); } cout << endl; } int main() { cin.tie(NULL)->sync_with_stdio(false); cin >> N >> M >> V; V -= 1; FOR(i, M) { int n0, n1; cin >> n0 >> n1; n0 -= 1, n1 -= 1; av[n0].push_back(n1); av[n1].push_back(n0); } dfs(); bfs(); return 0; }
'문제해결' 카테고리의 다른 글
백준 15663번: N과 M(9) (0) 2023.11.29 백준 1629번: 곱셈 (0) 2023.11.28 백준 11687번: 팩토리얼 0의 개수 (0) 2023.11.28 백준 23253번: 자료구조는 정말 최고야 (0) 2023.11.28 백준 9251번: LCS, 백준 5582번: 공통 부분 문자열 (2) 2023.11.20