๋ฌธ์
๊ทธ๋ํ๋ฅผ 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
ย
ย
๋ฌธ์ ํ๋ ธ๋ ์ด์
โ 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); } } }
ย