알고리즘

백준 14218번 그래프 탐색2 (JAVA)

박카스마시며코딩 2023. 9. 18. 19:05

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

 

14218번: 그래프 탐색 2

첫째 줄에는 도시의 개수 n,도로의 개수 m이 주어진다. 다음 m개의 줄에는 두 도시가 주어진다.(2≤n≤1,000,1≤m≤100,000) 다음 줄에는 도로 정비 계획에 들어가 있는 도로의 수 q가 주어지고, 다음 q

www.acmicpc.net

 

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

양방향 그래프이기 때문에 1에서 5로 가나 5에서 1로 가나 똑같은 가중치가 필요합니다.

그래서 저는 1부터 시작해서 나머지 노드에 가는데 얼마나 걸리는지를 판단하여 문제를 해결하였습니다.

 

package BOJ.bfs;

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

public class BOJ_14218 {

    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        Function<String,Integer> stoi = Integer::parseInt;
        int n = stoi.apply(st.nextToken());
        int m = stoi.apply(st.nextToken());
        List<Integer>[] list =  new List[n+1];
        for(int i = 0 ; 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);
        }
        int q= stoi.apply(br.readLine());
        for(int i = 0 ; i < q ; 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);
            int[] result = bfs(list,n);
            StringBuilder sb = new StringBuilder();
            for(int j = 1; j <= n ; j++){
                sb.append(result[j]+" ");
            }
            sb.setLength(sb.length()-1);
            System.out.println(sb.toString());
        }
    }
    private static final int NOT_VALID = -1;
    private static int[] bfs(List<Integer>[] list, int n) {
        Queue<Integer> q = new LinkedList<>();
        q.offer(1);
        boolean[]visited = new boolean[n+1];
        visited[1] = true;
        int[] result = new int[n+1];
        Arrays.fill(result,NOT_VALID);
        int time = 0;
        while(!q.isEmpty()){
            int size  = q.size();
            for(int s = 0; s < size ; s++){
                int now = q.poll();
                result[now] = time;
                for(int next : list[now]){
                    if(!visited[next]){
                        q.offer(next);
                        visited[next] = true;
                    }
                }
            }
            time++;
        }
        return result;
    }
}