DFS์™€ BFS (1260)

๋ฌธ์ œ

๊ทธ๋ž˜ํ”„๋ฅผ DFS๋กœ ํƒ์ƒ‰ํ•œ ๊ฒฐ๊ณผ์™€ BFS๋กœ ํƒ์ƒ‰ํ•œ ๊ฒฐ๊ณผ๋ฅผ ์ถœ๋ ฅํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค. ๋‹จ, ๋ฐฉ๋ฌธํ•  ์ˆ˜ ์žˆ๋Š” ์ •์ ์ด ์—ฌ๋Ÿฌ ๊ฐœ์ธ ๊ฒฝ์šฐ์—๋Š” ์ •์  ๋ฒˆํ˜ธ๊ฐ€ ์ž‘์€ ๊ฒƒ์„ ๋จผ์ € ๋ฐฉ๋ฌธํ•˜๊ณ , ๋” ์ด์ƒ ๋ฐฉ๋ฌธํ•  ์ˆ˜ ์žˆ๋Š” ์ ์ด ์—†๋Š” ๊ฒฝ์šฐ ์ข…๋ฃŒํ•œ๋‹ค.ย ์ •์  ๋ฒˆํ˜ธ๋Š” 1๋ฒˆ๋ถ€ํ„ฐ N๋ฒˆ๊นŒ์ง€์ด๋‹ค.

์ž…๋ ฅ

์ฒซ์งธ ์ค„์— ์ •์ ์˜ ๊ฐœ์ˆ˜ N(1 โ‰ค N โ‰ค 1,000), ๊ฐ„์„ ์˜ ๊ฐœ์ˆ˜ M(1 โ‰ค M โ‰ค 10,000), ํƒ์ƒ‰์„ ์‹œ์ž‘ํ•  ์ •์ ์˜ ๋ฒˆํ˜ธ V๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ๋‹ค์Œ M๊ฐœ์˜ ์ค„์—๋Š” ๊ฐ„์„ ์ด ์—ฐ๊ฒฐํ•˜๋Š” ๋‘ ์ •์ ์˜ ๋ฒˆํ˜ธ๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ์–ด๋–ค ๋‘ ์ •์  ์‚ฌ์ด์— ์—ฌ๋Ÿฌ ๊ฐœ์˜ ๊ฐ„์„ ์ด ์žˆ์„ ์ˆ˜ ์žˆ๋‹ค. ์ž…๋ ฅ์œผ๋กœ ์ฃผ์–ด์ง€๋Š” ๊ฐ„์„ ์€ ์–‘๋ฐฉํ–ฅ์ด๋‹ค.

์ถœ๋ ฅ

์ฒซ์งธ ์ค„์— DFS๋ฅผ ์ˆ˜ํ–‰ํ•œ ๊ฒฐ๊ณผ๋ฅผ, ๊ทธ ๋‹ค์Œ ์ค„์—๋Š” BFS๋ฅผ ์ˆ˜ํ–‰ํ•œ ๊ฒฐ๊ณผ๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค. V๋ถ€ํ„ฐ ๋ฐฉ๋ฌธ๋œ ์ ์„ ์ˆœ์„œ๋Œ€๋กœ ์ถœ๋ ฅํ•˜๋ฉด ๋œ๋‹ค.

์˜ˆ์ œ ์ž…๋ ฅ 1

4 5 1 1 2 1 3 1 4 2 4 3 4

์˜ˆ์ œ ์ถœ๋ ฅ 1

1 2 4 3 1 2 3 4

์˜ˆ์ œ ์ž…๋ ฅ 2

5 5 3 5 4 5 2 1 2 3 4 3 1

์˜ˆ์ œ ์ถœ๋ ฅ 2

3 1 2 5 4 3 1 4 2 5

์˜ˆ์ œ ์ž…๋ ฅ 3

1000 1 1000 999 1000

์˜ˆ์ œ ์ถœ๋ ฅ 3

1000 999 1000 999
ย 

ย 
notion image
๋ฌธ์ œํ‹€๋ ธ๋˜ ์ด์œ 
โ†’ for (int i = 1; i <= m; i++) { int a, b; cin >> a >> b; adjancent[a].push_back(b); adjancent[b].push_back(a); } for (int i = 1; i <= n; i++)
์ด๋ถ€๋ถ„ 1๋กœ ์•ˆํ•ด์ค˜์„œ ๋ฌธ์ œ์—์„œ 1๋ถ€ํ„ฐ ์‹œ์ž‘ํ•œ๋‹คํ–ˆ์Œ..
ย 
์ •๋‹ต์ฝ”๋“œ
#include<iostream> #include<algorithm> #include<vector> #include<queue> using namespace std; vector<vector<int>> adjancent; vector<bool> discorverd; void dfs(int here); void bfs(int here); int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); adjancent = vector<vector<int>>(10001); discorverd = vector<bool>(1001, false); int n, m, v; cin >> n >> m >> v; for (int i = 1; i <= m; i++) { int a, b; cin >> a >> b; adjancent[a].push_back(b); adjancent[b].push_back(a); } for (int i = 1; i <= n; i++) { sort(adjancent[i].begin(),adjancent[i].end()); } dfs(v); discorverd = vector<bool>(1001, false); cout << '\n'; bfs(v); } void dfs(int here) { //์žฌ๊ท€ if (discorverd[here] == true) return; discorverd[here] = true; cout << here << " "; for (int i = 0; i < adjancent[here].size(); i++) { dfs(adjancent[here][i]); } } void bfs(int here) { //ํ queue<int> q; q.push(here); discorverd[here] = true; while (q.empty() == false) { here = q.front(); q.pop(); cout << here << " "; for (int there : adjancent[here]) { if (discorverd[there] == true) continue; discorverd[there] = true; q.push(there); } } }
ย