[๋ฐฑ์ค] DFS์ BFS
[๋ฐฑ์ค] DFS์ BFS
๋ฌธ์
๋งํฌ : BOJ
๊ทธ๋ํ๋ฅผ DFS๋ก ํ์ํ ๊ฒฐ๊ณผ์ BFS๋ก ํ์ํ ๊ฒฐ๊ณผ๋ฅผ ์ถ๋ ฅํ๋ ํ๋ก๊ทธ๋จ์ ์์ฑํ์์ค. ๋จ, ๋ฐฉ๋ฌธํ ์ ์๋ ์ ์ ์ด ์ฌ๋ฌ ๊ฐ์ธ ๊ฒฝ์ฐ์๋ ์ ์ ๋ฒํธ๊ฐ ์์ ๊ฒ์ ๋จผ์ ๋ฐฉ๋ฌธํ๊ณ , ๋ ์ด์ ๋ฐฉ๋ฌธํ ์ ์๋ ์ ์ด ์๋ ๊ฒฝ์ฐ ์ข ๋ฃํ๋ค. ์ ์ ๋ฒํธ๋ 1๋ฒ๋ถํฐ N๋ฒ๊น์ง์ด๋ค.
ํ์ด
๋๋ฌด ์ค๋๋ง์ ํ๋ ค๊ณ ํ๋๊น ๋ค ์์ด๋ฒ๋ ค์,, ๋ค์ ๋์ ์ฌ ๋ดค๋ค.
-
DFS : Depth-first Search ๋ก ๊น์ด ์ฐ์ ํ์์ ๋งํ๋ค.
ํ ๋ ธ๋๊ฐ ์ ํ๋๋ฉด ๋ ธ๋์ ์ฐ๊ฒฐ๋ ์ฒซ๋ฒ์งธ ๋ ธ๋๋ถํฐ ํ์ํ๋ค. -
BFS : Breadth-first Search ๋ก ๋๋น ์ฐ์ ํ์์ ๋งํ๋ค.
ํ ๋ ธ๋๊ฐ ์ ํ๋๋ฉด ๋ ธ๋์ ์ฐ๊ฒฐ๋ ๋ชจ๋ ๋ ธ๋๋ค์ ํ์ํ๋ค. -
DFS๋ ํจ์๋ฅผ ๋ค์ ์ฐพ์๊ฐ๋ ์ฌ๊ท ๋ฐฉ์์ผ๋ก ํ์ํ๋ค.
BFS๋ ํจ์์์ ๋ชจ๋ ๋ ธ๋๋ฅผ ํ์ํ๋ฉด์ queue์ ์ ์ฅํ๊ณ ์ฐพ์๊ฐ๋ค.
#include<iostream>
#include<vector>
#include<algorithm>
#include<queue>
using namespace std;
//DFS์ BFS
int visited[1001] = { false };
vector<vector<int>> v(1001);
queue<int> q;
int n, m, start;
void dfs(int s) {
visited[s] = true;
cout << s << " ";
for (int i = 0; i < v[s].size(); i++)
{
if (visited[v[s].at(i)] == true)
continue;
int next = v[s].at(i);
dfs(next);
}
}
void bfs() {
q.push(start);
visited[start] = true;
while (!q.empty())
{
start = q.front();
q.pop();
cout << start << " ";
for (int i = 0; i < v[start].size(); i++)
{
if (visited[v[start].at(i)])
continue;
q.push(v[start].at(i));
visited[v[start].at(i)] = true;
}
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie();
cin >> n >> m >> start;
int s = start;
for (int i = 0; i < m; i++)
{
int x, y;
cin >> x >> y;
for (int j = 0; j < n; j++)
{
if (j == x - 1)
{
v[x].push_back(y);
v[y].push_back(x);
break;
}
}
}
for (int i = 0; i < n; i++)
sort(v[i].begin(), v[i].end());
dfs(s);
for (int i = 0; i <= n; i++)
visited[i] = false;
cout << endl;
bfs();
return 0;
}
์ค์ํ๋ ์
bfs์์ return์ ํจ์๋ฅผ ๋ถ์ฌ์.. ์๊พธ fail์ด ๋ฌ๋ค. ์.. return์ ํด์ ํจ์๊ฐ ๋ฐ๋ก ๋๋๋ ๋ฏ ์ถ๋ค. ๋ค๋ฅธ ์์์ ! ์๋ฌดํผ ๋ณต์ต ๋ค์ ์์!