-
프로그래머스: 네트워크코딩 2020. 6. 4. 12:00
문제
네트워크란 컴퓨터 상호 간에 정보를 교환할 수 있도록 연결된 형태를 의미합니다. 예를 들어, 컴퓨터 A와 컴퓨터 B가 직접적으로 연결되어있고, 컴퓨터 B와 컴퓨터 C가 직접적으로 연결되어 있을 때 컴퓨터 A와 컴퓨터 C도 간접적으로 연결되어 정보를 교환할 수 있습니다. 따라서 컴퓨터 A, B, C는 모두 같은 네트워크 상에 있다고 할 수 있습니다.
컴퓨터의 개수 n, 연결에 대한 정보가 담긴 2차원 배열 computers가 매개변수로 주어질 때, 네트워크의 개수를 return 하도록 solution 함수를 작성하시오.
입출력 예
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 코드
class Solution { static boolean[] check; public int solution(int n, int[][] computers) { int answer = 0; check = new boolean[computers.length]; for(int i=0; i<n; i++){ if(check[i] == false) { answer++; dfs(computers, i); } } return answer; } public static void dfs(int[][] computers, int index){ check[index] = true; for(int i=0; i<computers.length; i++){ if(computers[i][index] == 1 && check[i] == false) dfs(computers, i); } } }
'코딩' 카테고리의 다른 글
프로그래머스: 어린 동물 찾기 (0) 2020.06.06 프로그래머스: 동물 수 구하기 (0) 2020.06.05 프로그래머스: 여러 기준으로 정렬하기 (0) 2020.06.05 프로그래머스: 타겟 넘버 (1) 2020.06.03 백준 1260번: DFS와 BFS (1) 2020.06.02