Notice
Recent Posts
Recent Comments
Link
«   2026/06   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
Archives
Today
Total
관리 메뉴

dh-winternagi 님의 블로그

(24479) 알고리즘 수업 - 깊이 우선 탐색 1 본문

백준 (C++)/Solve

(24479) 알고리즘 수업 - 깊이 우선 탐색 1

dh-winternagi 2026. 4. 18. 22:28

https://www.acmicpc.net/problem/24479

단계별로 풀어보기

27단계(그래프와 순회) 1번째

 

 

 

PS에서 정말 많이 나오는 그래프다. 그래프, DFS, BFS 등을 설명하기에는 끝도 없으므로 그래프 문제에서 문제풀이에 대한 설명이 아닌 개념에 대한 설명은 최대한 생략한다.

 

 

 

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
  ios::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  
  int n, m, r, x= 1;
  
  cin >> n >> m >> r;
  
  vector adj(n+1, vector<int>());
  vector<int> visited(n+1);
  
  while(m--){
    int u, v;
    
    cin >> u >> v;
    
    adj[u].push_back(v);
    adj[v].push_back(u);
  }
  
  for(int i=1;i<=n;i++)  sort(adj[i].begin(), adj[i].end());
  
  auto dfs= [&](auto self, int now) -> void {
    visited[now]= x++;
    
    for(int next:adj[now]){
      if(visited[next])  continue;
      
      self(self, next);
    }
  };
  
  dfs(dfs, r);
  
  for(int i=1;i<=n;i++)  cout << visited[i] << "\n";
  
  return 0;
}

'백준 (C++) > Solve' 카테고리의 다른 글

(24444) 알고리즘 수업 - 너비 우선 탐색 1  (0) 2026.04.18
(24480) 알고리즘 수업 - 깊이 우선 탐색 2  (0) 2026.04.18
(1202) 보석 도둑  (0) 2026.04.18
(2696) 중앙값 구하기  (0) 2026.04.18
(2075) N번째 큰 수  (0) 2026.04.18