코테/99클럽

99클럽 코테 스터디 6일차 TIL + DFS/BFS

imname1am 2025. 1. 15. 23:59
반응형

 

문제

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

 

 

코드

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import java.util.*;
import java.io.*;
 
public class Main {
    static int N,M,V;
    static boolean[] visited;
    static ArrayList<Integer>[] list;
    static StringBuilder sb = new StringBuilder();
    
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine(), " ");
        
        N = Integer.parseInt(st.nextToken());
        M = Integer.parseInt(st.nextToken());
        V = Integer.parseInt(st.nextToken());
        
        list = new ArrayList[N+1];
        for(int i = 1 ; i <= N ; i++) {
            list[i] = new ArrayList<>();
        }
        
        for(int i = 0 ; i < M ; i++) {
            st = new StringTokenizer(br.readLine(), " ");
            int a = Integer.parseInt(st.nextToken());
            int b = Integer.parseInt(st.nextToken());
            
            list[a].add(b);
            list[b].add(a);
        }
        
        for(int i = 1 ; i <= N ; i++) {
            Collections.sort(list[i]);
        }
        
        visited = new boolean[N+1];
        dfs(V, 0);
 
        sb.append("\n");
        
        visited = new boolean[N+1];
        bfs(V);
        
        System.out.println(sb.toString());
    }
    
    private static void dfs(int idx, int depth) {
        if(depth == N) {
            return;
        }
        
        visited[idx] = true;
        sb.append(idx + " ");
        
        for(int next : list[idx]) {
            if(!visited[next]) {
                dfs(next, depth + 1);
            }
        }
    }
    
    private static void bfs(int idx) {
        Queue<Integer> q = new LinkedList<>();
        q.add(idx);
        
        visited[idx] = true;
        
        while(!q.isEmpty()) {
            int now = q.poll();
            sb.append(now + " ");
            
            for(int next : list[now]) {
                if(!visited[next]) {
                    visited[next] = true;
                    q.add(next);
                }
            }
        }
    }
}
cs
 
 

 

오늘의 학습 키워드

: DFS/BFS

 

공부한 내용 본인의 언어로 정리하기

- DFS : 현재 위치와 연결된 점의 흐름을 따라 방문하기 (깊이 우선 탐색)

- BFS : 현재 위치와 연결된 점들 中 방문한 적 없는 점 순차적으로 방문하기 (너비 우선 탐색)

 

오늘의 회고

- 저엉말 오랜만의 DFS, BFS 문제였다... 반갑기도 하면서 알고리즘 기억이 어렴풋이 났다..

 

 - 어떤 문제가 있었고, 나는 어떤 시도를 했는지

- DFS 작성하는 부분에서 잠깐 헷갈려서 다시 생각해보고, 기존에 제출한 코드를 참고했다.

 

 

  - 어떻게 해결했는지

: 내가 기존에 제출한 코드들 보고 어디에서 잘못 됐는지 잡았다.


  -  무엇을 새롭게 알았는지

: X

 

  - 내일 학습할 것은 무엇인지

: DFS 알고리즘 복습하기!

반응형