๐ ๋ฌธ์
https://www.acmicpc.net/problem/1260
๐ ๋ฌธ์ ์์ฝ
๊ทธ๋ํ๋ฅผ DFS๋ก ํ์ํ ๊ฒฐ๊ณผ์ BFS๋ก ํ์ํ ๊ฒฐ๊ณผ๋ฅผ ์ถ๋ ฅํ๋ ํ๋ก๊ทธ๋จ์ ์์ฑํ์์ค. ๋จ, ๋ฐฉ๋ฌธํ ์ ์๋ ์ ์ ์ด ์ฌ๋ฌ ๊ฐ์ธ ๊ฒฝ์ฐ์๋ ์ ์ ๋ฒํธ๊ฐ ์์ ๊ฒ์ ๋จผ์ ๋ฐฉ๋ฌธํ๊ณ , ๋ ์ด์ ๋ฐฉ๋ฌธํ ์ ์๋ ์ ์ด ์๋ ๊ฒฝ์ฐ ์ข ๋ฃํ๋ค. ์ ์ ๋ฒํธ๋ 1๋ฒ๋ถํฐ N๋ฒ๊น์ง์ด๋ค.
์ ๋ ฅ: ์ฒซ์งธ ์ค์ ์ ์ ์ ๊ฐ์ N(1 โค N โค 1,000), ๊ฐ์ ์ ๊ฐ์ M(1 โค M โค 10,000), ํ์์ ์์ํ ์ ์ ์ ๋ฒํธ V๊ฐ ์ฃผ์ด์ง๋ค. ๋ค์ M๊ฐ์ ์ค์๋ ๊ฐ์ ์ด ์ฐ๊ฒฐํ๋ ๋ ์ ์ ์ ๋ฒํธ๊ฐ ์ฃผ์ด์ง๋ค. ์ด๋ค ๋ ์ ์ ์ฌ์ด์ ์ฌ๋ฌ ๊ฐ์ ๊ฐ์ ์ด ์์ ์ ์๋ค. ์ ๋ ฅ์ผ๋ก ์ฃผ์ด์ง๋ ๊ฐ์ ์ ์๋ฐฉํฅ์ด๋ค
์ถ๋ ฅ: ์ฒซ์งธ ์ค์ DFS๋ฅผ ์ํํ ๊ฒฐ๊ณผ๋ฅผ, ๊ทธ ๋ค์ ์ค์๋ BFS๋ฅผ ์ํํ ๊ฒฐ๊ณผ๋ฅผ ์ถ๋ ฅํ๋ค. V๋ถํฐ ๋ฐฉ๋ฌธ๋ ์ ์ ์์๋๋ก ์ถ๋ ฅํ๋ฉด ๋๋ค.
๐ก ์ ๊ทผ ๋ฐฉ๋ฒ
set์ ์ด์ฉํด ๋
ธ๋ ๊ตฌ์กฐ์ฒด๋ฅผ ์์๋ก ๋ง๋ค์๊ณ ,
map์ ์ด์ฉํด ๊ทธ๋ํ๋ฅผ ์ค๊ณ ํ๋ค.
โ ๏ธ ์ฒ์์ ํ๋ ์ค์
4 4 1
1 2
1 3
2 3
3 4
bfs ์กฐ๊ฑด ์ฒดํฌ ํ์ด๋ฐ์ ์๋ชป ๋์ด ์๋ฌ๊ฐ ๋ฌ๋ ํ ์คํธ์ผ์ด์ค์ด๋ค.
๐ป ์ฝ๋
#include <iostream>
#include <map>
#include <set>
using namespace std;
int N, M, V;
struct Node {
public:
void push(int n) { lines.emplace(n); }
bool isContain(int n) { return lines.find(n) != lines.end(); }
void setDFS() { isDFS = true; }
bool getDFS() { return isDFS; }
void setBFS() { isBFS = true; }
bool getBFS() { return isBFS; }
private:
set<int> lines;
bool isDFS = false, isBFS = false;
};
map<int, Node> graph;
void dfs(int root) {
cout << root;
graph[root].setDFS();
for (int i = 1; i <= N; ++i) {
if (graph[root].isContain(i) == false)
continue;
if (graph[i].getDFS())
continue;
cout << " ";
dfs(i);
}
return;
}
void bfs(int root) {
int target[1001] = {0};
target[0] = root;
int cnt = 0;
int index = 1;
while (target[cnt] != 0) {
cout << target[cnt];
graph[target[cnt]].setBFS();
for (int i = 1; i <= N; ++i) {
if (graph[target[cnt]].isContain(i) == false)
continue;
if (graph[i].getBFS())
continue;
if (index >= N)
break;
graph[i].setBFS();
target[index] = i;
index++;
}
cnt++;
if (target[cnt] == 0)
return;
cout << " ";
}
return;
}
int main() {
cin >> N >> M >> V;
for (int i = 1; i <= N; ++i) {
graph.emplace(i, Node());
}
for (int i = 0; i < M; ++i) {
int key, value;
cin >> key >> value;
graph[key].push(value);
graph[value].push(key);
}
dfs(V);
cout << '\n';
bfs(V);
return 0;
}