Home > Algorithm > BOJ > [BOJ] 1260๋ฒˆ DFS์™€ BFS

[BOJ] 1260๋ฒˆ DFS์™€ BFS
C++ ๋ฐฑ์ค€ BOJ ์•Œ๊ณ ๋ฆฌ์ฆ˜ Algorithm

๐Ÿ”— ๋ฌธ์ œ

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;
}