본문 바로가기
코딩테스트

[백준 9372] 상근이의 여행 [java]

by 근즈리얼 2021. 3. 31.
728x90


이 문제는 간단한게 bfs문제로 풀면 가능한 문제다.

배열을 만들때 1부터 시작한다는 것만 생각해주면 된다!

 

코드

package baekjoon;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class sanggeun_travel {
    static int arr[][];
    static boolean visit[];
    static int country, line, result;

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        for(int i = 0; i<n;i++){
            country = sc.nextInt();
            line = sc.nextInt();

            result = 0;

            arr = new int[country+1][country+1];
            visit = new boolean[country+1];

            for(int j = 0; j<line;j++){
                int a = sc.nextInt();
                int b = sc.nextInt();
                arr[a][b] = 1;
                arr[b][a] = 1;
            }
            bfs();
            System.out.println(result-1);
        }
    }

    private static void bfs() {
        Queue<Integer> queue = new LinkedList<>();
        queue.add(1);
        visit[1] = true;
        while(!queue.isEmpty()){
            result++;
            int cur = queue.poll();
            for(int i = 1; i<=country;i++){
                if(arr[cur][i] == 1 && !visit[i]){
                    visit[i] = true;
                    queue.add(i);
                }
            }
        }
    }
}
728x90

'코딩테스트' 카테고리의 다른 글

[백준 9370] 미확인 도착지[java]  (0) 2021.04.08
[백준4386] 별자리 만들기 [java]  (0) 2021.03.31
[백준1707] 이분 그래프 [java]  (0) 2021.03.28
[백준7569] 토마토 [java]  (0) 2021.03.27
[백준7576] 토마토[java]  (0) 2021.03.23

댓글