Algorithm (Java)/문제풀이
[자바/Java] 프로그래머스 -네트워크 (Level3 - BFS)
무럭무럭새싹
2023. 3. 4. 12:46
https://school.programmers.co.kr/learn/courses/30/lessons/43162
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
문제 설명
네트워크란 컴퓨터 상호 간에 정보를 교환할 수 있도록 연결된 형태를 의미합니다. 예를 들어, 컴퓨터 A와 컴퓨터 B가 직접적으로 연결되어있고, 컴퓨터 B와 컴퓨터 C가 직접적으로 연결되어 있을 때 컴퓨터 A와 컴퓨터 C도 간접적으로 연결되어 정보를 교환할 수 있습니다. 따라서 컴퓨터 A, B, C는 모두 같은 네트워크 상에 있다고 할 수 있습니다.
컴퓨터의 개수 n, 연결에 대한 정보가 담긴 2차원 배열 computers가 매개변수로 주어질 때, 네트워크의 개수를 return 하도록 solution 함수를 작성하시오.
제한사항- 컴퓨터의 개수 n은 1 이상 200 이하인 자연수입니다.
- 각 컴퓨터는 0부터 n-1인 정수로 표현합니다.
- i번 컴퓨터와 j번 컴퓨터가 연결되어 있으면 computers[i][j]를 1로 표현합니다.
- computer[i][i]는 항상 1입니다.
3 | [[1, 1, 0], [1, 1, 0], [0, 0, 1]] | 2 |
3 | [[1, 1, 0], [1, 1, 1], [0, 1, 1]] | 1 |
예제 #1
아래와 같이 2개의 네트워크가 있습니다.

예제 #2
아래와 같이 1개의 네트워크가 있습니다.

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