Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | |
7 | 8 | 9 | 10 | 11 | 12 | 13 |
14 | 15 | 16 | 17 | 18 | 19 | 20 |
21 | 22 | 23 | 24 | 25 | 26 | 27 |
28 | 29 | 30 |
Tags
- Lifting State Up
- State
- java
- batch udpate
- codility
- BOJ2042
- DB Navigator
- 객체지향 설계 5원칙
- useContext
- 리액트의 작동방식
- React 훅 사용규칙
- 프로그래머스#JAVA
- rest operator
- 리액트 성능 최적화
- spread operator
- state update scheduling
- 섬 연결하기
- 프로그래머스
- MST구현
- Greedy
- Modern Javascript
- react
- Kruskal Algorithm
- 리액트 상태값 업데이트
- Segment Tree
- heap
- useState
- JS Array Functions
- useReducer
- DFS
Archives
- Today
- Total
개발하는SM
[프로그래머스] 네트워크 본문
programmers.co.kr/learn/courses/30/lessons/43162
코딩테스트 연습 - 네트워크
네트워크란 컴퓨터 상호 간에 정보를 교환할 수 있도록 연결된 형태를 의미합니다. 예를 들어, 컴퓨터 A와 컴퓨터 B가 직접적으로 연결되어있고, 컴퓨터 B와 컴퓨터 C가 직접적으로 연결되어 있
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입니다.
풀이
전형적인 그래프 표현 + BFS 문제이다
1. 인접 리스트 형태로 그래프를 저장한다.
2. 저장된 그래프를 BFS 순회하면서 네트워크의 개수를 구한다.
자바로 ArrayList 배열을 만드는 구문은 항상 헷갈리는 것 같다;;
import java.util.*;
class Solution {
// 그래프를 표현할 인접 리스트
public static ArrayList<Integer> A[];
public boolean visited[];
public void BFS(int start){
Queue<Integer> q = new LinkedList<Integer>();
q.offer(start);
visited[start] = true;
while(!q.isEmpty()){
int front = q.poll();
for(int i=0; i<A[front].size(); i++){
if(!visited[A[front].get(i)]){
q.offer(A[front].get(i));
visited[A[front].get(i)] = true;
}
}
}
return;
}
public int solution(int n, int[][] computers) {
int answer = 0;
A = (ArrayList<Integer>[])new ArrayList[n];
visited = new boolean[n];
for(int i=0; i<n; i++){
A[i] = new ArrayList<Integer>();
}
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
if(i == j) continue;
if(computers[i][j] == 1){
A[i].add(j);
}
}
}
for(int i=0; i<n; i++){
if(!visited[i]){
answer++;
BFS(i);
}
}
return answer;
}
}
'Algorithm > DFS, BFS' 카테고리의 다른 글
[프로그래머스] 여행 경로(DFS 풀이) (0) | 2021.02.17 |
---|---|
[프로그래머스] 단어 변환 (0) | 2021.02.17 |
[프로그래머스] 타겟 넘버 (0) | 2021.02.16 |