백준_바이러스

LeeYulhee·2023년 8월 30일
0

💻 문제 출처 : 백준_바이러스

👉 내가 작성한 답


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        
        int computer = Integer.parseInt(br.readLine());
        int connect = Integer.parseInt(br.readLine());
        
        Map<Integer, List<Integer>> map = new HashMap<>();
        
        for(int i = 0; i < connect; i++) {
            String[] strArray = br.readLine().split(" ");
            
            map.computeIfAbsent(Integer.parseInt(strArray[0]), k -> new ArrayList<>()).add(Integer.parseInt(strArray[1]));
            map.computeIfAbsent(Integer.parseInt(strArray[1]), k -> new ArrayList<>()).add(Integer.parseInt(strArray[0]));
        }
        
        Queue<Integer> queue = new LinkedList<>();
        boolean[] check = new boolean[computer + 1];
        int count = 0;
        
        queue.add(1);
        check[1] = true;
        
        while(!queue.isEmpty()) {
            int num = queue.poll();
            
            if(map.get(num) != null) {
                for(int i : map.get(num)) {
                    if(check[i] == false) {
                        queue.add(i);
                        check[i] = true;
                        count++;
                    }
                }
            }
        }
        
        System.out.println(count);
    }
}

📌 문제 풀이 설명

  • BufferedReader를 생성
  • 첫 번째 입력 값을 int로 변환해 computer 변수에 대입
  • 두 번째 입력 값을 int로 변환해 connect 변수에 대입
  • Integer로 Key로, List를 Value로 갖는 Map을 생성
  • for문으로 0부터 connect 미만까지 1씩 증가하며 순회
    • 입력된 값을 “ “로 나눠 String 배열 strArray에 저장
    • computeIfAbsent 메서드를 사용해서 해당 Key(strArray[0]을 int로 변환한 값)가 Map에 없으면 ArrayList를 생성해서 넣고, 아니면 해당 Key의 Value를 불러옴 → strArray[1] 값을 List에 추가
    • 반대로 Key가 strArray[1]인 경우 Value에 strArray[0]을 추가할 수 있게도 작성
  • Queue를 생성
  • boolean 배열 check를 computer + 1의 길이로 생성
    • 해당 숫자를 방문했는지 인덱스를 이용해 확인할 예정이라 인덱스가 computer까지 있어야 함
  • int 변수 count를 생성하고 0으로 초기화한 뒤, queue에 1을 추가하고 check[1]에 true를 대입
  • while문으로 queue가 비어있지 않은 동안 순회
    • int 변수 num에 queue의 첫 번째 값을 대입하고 queue에서 삭제
    • 만약 map.get(num)으로 가져온 List가 null이 아니라면
      • 향상된 for문으로 해당 List를 순회
        • 만약 List의 요소에 해당하는 check 배열의 값이 false라면(확인하지 않은 경우)
          • queue에 i를 추가
          • check[i]에 true 대입
          • count를 1 증가
  • for문 종료 후 count 값을 출력
profile
공부 중인 신입 백엔드 개발자입니다

0개의 댓글