https://programmers.co.kr/learn/courses/30/lessons/43162?language=java
코딩테스트 연습 - 네트워크
네트워크란 컴퓨터 상호 간에 정보를 교환할 수 있도록 연결된 형태를 의미합니다. 예를 들어, 컴퓨터 A와 컴퓨터 B가 직접적으로 연결되어있고, 컴퓨터 B와 컴퓨터 C가 직접적으로 연결되어 있
programmers.co.kr
기본적인 그래프 탐색에 대한 문제이다. 전체적인 그래프의 구성 영역을 구하면 되는 것이기 때문에 BFS(Queue)를 이용해서 해결할 수 있었다.
문제 및 제한사항
예제
코드
import java.util.LinkedList;
import java.util.Queue;
class Solution
{
// 시작 노드를 기준으로 BFS 실행
public static int makegraph(int[][] computers, boolean[] visit, int n, int start)
{
Queue<Integer> q = new LinkedList<Integer>();
q.add(start);
visit[start] = true;
while(!q.isEmpty())
{
int index = q.poll();
for(int i=0; i<n; i++)
{
if(computers[index][i]==1 && !visit[i])
{
visit[i] = true;
q.add(i);
}
}
}
return 1;
}
public int solution(int n, int[][] computers)
{
boolean[] visit = new boolean[n];
int answer = 0;
// 방문하지 않은 정점을 시작 인덱스로 하는 BFS 호출
for(int i=0; i<n; i++)
{
if(!visit[i])
{
answer += makegraph(computers, visit, n, i);
}
}
return answer;
}
}
'[ 다먹살 ] > - Coding' 카테고리의 다른 글
[백준] 13458 시험 감독 (0) | 2021.11.22 |
---|---|
[백준] 2163 초콜릿 자르기 (0) | 2021.11.22 |
[백준] 7576 토마토 (0) | 2021.11.19 |
[백준] 2583 영역 구하기 (0) | 2021.11.18 |
[백준] 4963 섬의 개수 (0) | 2021.11.18 |
댓글