[Algorithm] 프로그래머스_네트워크(JAVA)

2024. 12. 11. 17:49·Algorithm

https://school.programmers.co.kr/learn/courses/30/lessons/43162

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr


문제 이해 잘못해서 시간을 꽤 쓴 문제다.

 

처음엔 2차원 방문 배열이 필요하다고 생각했는데,

각 컴퓨터의 방문 여부만 체크하면 되므로 1차원 배열으로도 충분함을 깨달았다.

 

0~n번까지의 컴퓨터가 있다면

0번 컴퓨터부터 큐에 넣고 0번과 연결되어 있는 컴퓨터를 찾는다.

그 컴퓨터를 큐에 넣는다.

위 과정을 반복하는 로직을 구현하면 된다~

 

이때, 0-1, 0-3, 3-2 가 연결되어 있다면 하나의 네트워크이다.

computers : [[1, 1, 0, 1], [1, 1, 0, 0], [0, 0, 1, 1], [1, 0, 1, 1]]

return : 1

 

풀이는 아래와 같다.

import java.util.*;
class Solution {
    boolean[] visited;
    public int solution(int n, int[][] computers) {
        int answer = 0;
        visited = new boolean[n];
        
        for(int i = 0; i < n; i++){
            if(computers[i][i] == 1 && !visited[i]){
                answer++;
                bfs(i, n, computers);
            }
        }
        
        return answer;
    }
    
    void bfs(int x, int n, int[][] computers){
        visited[x] = true;
        
        Queue<Integer> q = new LinkedList<>();
        q.add(x);
        while(!q.isEmpty()){
            int target = q.poll();
            for(int i = 0; i < n; i++){
                if(!visited[i] && computers[i][target] == 1){
                    visited[i] = true;
                    q.add(i);
                }
            }
        }
        
    }
}

'Algorithm' 카테고리의 다른 글

[Algorithm] 프로그래머스_체육복(JAVA)  (0) 2024.12.13
[Algorithm] 프로그래머스_완주하지 못한 선수(JAVA)  (0) 2024.12.13
[Algorithm] 프로그래머스_K번째수(JAVA)  (2) 2024.12.11
[Algorithm] 프로그래머스_올바른 괄호(JAVA)  (3) 2024.12.10
[Algorithm] 프로그래머스_타겟넘버(JAVA)  (3) 2024.12.10
'Algorithm' 카테고리의 다른 글
  • [Algorithm] 프로그래머스_체육복(JAVA)
  • [Algorithm] 프로그래머스_완주하지 못한 선수(JAVA)
  • [Algorithm] 프로그래머스_K번째수(JAVA)
  • [Algorithm] 프로그래머스_올바른 괄호(JAVA)
dev_ajrqkq
dev_ajrqkq
알고리즘 천재가 될 거야
  • dev_ajrqkq
    기록이 자산이다
    dev_ajrqkq
  • 전체
    오늘
    어제
    • 분류 전체보기 (138)
      • Front-end (0)
      • Back-end (11)
        • Spring (1)
        • Java (8)
      • CS (9)
        • 데이터베이스 (5)
        • 네트워크 (4)
      • Algorithm (71)
      • 이것저것 (0)
      • 버그잡기 (1)
      • TIL (37)
      • 후기 (1)
      • 취준 (0)
  • 블로그 메뉴

    • 링크

    • 공지사항

    • 인기 글

    • 태그

      티스토리챌린지
      개발자취업
      Til
      99클럽
      오블완
      코딩테스트준비
      TypeScript
      항해99
    • 최근 댓글

    • 최근 글

    • hELLO· Designed By정상우.v4.10.2
    dev_ajrqkq
    [Algorithm] 프로그래머스_네트워크(JAVA)
    상단으로

    티스토리툴바