문제 설명
네트워크란 컴퓨터 상호 간에 정보를 교환할 수 있도록 연결된 형태를 의미합니다. 예를 들어, 컴퓨터 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입니다.
n | computers | return |
3 | [[1, 1, 0], [1, 1, 0], [0, 0, 1]] | 2 |
3 | [[1, 1, 0], [1, 1, 1], [0, 1, 1]] | 1 |
DFS 소스코드 (Java)
import java.util.Arrays;
class Solution {
private static int[] visited;
private static int []dx = {0, 1, 0, -1};
private static int []dy = {1, 0, -1, 0};
public int solution(int n, int[][] computers) {
int answer = 0;
visited = new int[n];
Arrays.fill(visited, 0);
for(int i =0; i<n; i++){
for(int j =0; j<n; j++){
if(computers[i][j]==1&&visited[j]==0){
func(computers, i, j, n);
answer++;
}
}
}
return answer;
}
public void func(int[][] board, int x, int y, int n){
visited[y]=1;
for(int i =0; i<n; i++){
if(visited[i]==0&&board[y][i]==1){
func(board, y, i, n);
}
}
}
public boolean check(int x, int y, int n){
if(0>x||0>y||x>=n||y>=n)
return false;
return true;
}
}
BFS 소스코드(java)
import java.util.Arrays;
import java.util.Queue;
import java.util.LinkedList;
class Solution {
public int solution(int n, int[][] computers) {
int answer = 0;
int []visited = new int[n];
for(int i=0; i<n; i++){
for(int j =0; j<n; j++){
if(computers[i][j]==1 && visited[j]==0){
visited[i] = 1;
Queue<Integer> q = new LinkedList<>();
q.add(j);
visited[j] = 1;
answer++;
while(q.peek()!=null){
int now = q.poll();
for(int k = 0; k< n; k++){
if(computers[now][k]==1 && visited[k]==0){
q.add(k);
visited[k] = 1;
}
}
}
}
}
}
return answer;
}
}
728x90
반응형
'개발자 :-) > 프로그래머스' 카테고리의 다른 글
[프로그래머스] 동적계획법 > 정수 삼각형 (Java) (0) | 2022.09.04 |
---|---|
[프로그래머스] 완전탐색 > 카펫 (0) | 2022.09.04 |
[프로그래머스] 2022 KAKAO TECH Internship > 등산코스 정하기 (0) | 2022.08.29 |
[프로그래머스] 스택/큐 > 기능개발(C++, Java) (0) | 2022.08.29 |
댓글