알고리즘

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

박카스마시며코딩 2023. 9. 29. 19:51

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

 

24479번: 알고리즘 수업 - 깊이 우선 탐색 1

첫째 줄에 정점의 수 N (5 ≤ N ≤ 100,000), 간선의 수 M (1 ≤ M ≤ 200,000), 시작 정점 R (1 ≤ R ≤ N)이 주어진다. 다음 M개 줄에 간선 정보 u v가 주어지며 정점 u와 정점 v의 가중치 1인 양

www.acmicpc.net

 

저는 dfs를 통해 문제를 해결하였습니다.

dfs를 통해 방문하지 않은 곳을 방문하면서 몇번째에 방문하는지를 체크하여 문제를 해결하였습니다.

 

package BOJ.dfs;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.function.Function;

public class BOJ_24479 {
    private static int NUMBER = 1;
    private static final int NOT_VISITED = 0;
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        Function<String,Integer> stoi = Integer::parseInt;
        StringTokenizer st = new StringTokenizer(br.readLine());
        int n = stoi.apply(st.nextToken());
        int m = stoi.apply(st.nextToken());
        int start = stoi.apply(st.nextToken());
        List<Integer> list[] = new List[n+1];
        for(int i = 1 ; i <= n ; i++){
            list[i] = new LinkedList<>();
        }
        for(int i = 0 ; i < m ; i++){
            st = new StringTokenizer(br.readLine());
            int a = stoi.apply(st.nextToken());
            int b = stoi.apply(st.nextToken());
            list[a].add(b);
            list[b].add(a);
        }
        for(int i = 1 ; i <= n ; i++){
            Collections.sort(list[i]);
        }
        int[] arrived = new int[n+1];
        dfs(start,list,arrived);
        for(int i = 1 ; i <= n ; i++){
            System.out.println(arrived[i]);
        }
    }

    private static void dfs(int now, List<Integer>[] list, int[] arrived) {
        arrived[now] = NUMBER++;
        for(int next : list[now]){
            if(arrived[next] == NOT_VISITED){
                dfs(next,list,arrived);
            }
        }
    }
}

'알고리즘' 카테고리의 다른 글

백준 15720번 카우버거 (JAVA)  (0) 2023.10.01
백준 2014번 소수의 곱 (JAVA)  (0) 2023.09.30
백준 1475번 방 번호 (JAVA)  (0) 2023.09.28
백준 1183번 약속 (JAVA)  (0) 2023.09.27
프로그래머스 조건 문자열 (JAVA)  (0) 2023.09.26