[Programmers] 네트워크 (Java)

오태호·2022년 11월 14일
0

프로그래머스

목록 보기
15/56

1.  문제 링크

https://school.programmers.co.kr/learn/courses/30/lessons/43162

2.  문제

네트워크란 컴퓨터 상호 간에 정보를 교환할 수 있도록 연결된 형태를 의미합니다. 예를 들어, 컴퓨터 A와 컴퓨터 B가 직접적으로 연결되어있고, 컴퓨터 B와 컴퓨터 C가 직접적으로 연결되어 있을 때 컴퓨터 A와 컴퓨터 C도 간접적으로 연결되어 정보를 교환할 수 있습니다. 따라서 컴퓨터 A, B, C는 모두 같은 네트워크 상에 있다고 할 수 있습니다.

컴퓨터의 개수 n, 연결에 대한 정보가 담긴 2차원 배열 computers가 매개변수로 주어질 때, 네트워크의 개수를 return 하도록 solution 함수를 작성하시오.

3.  제한사항

  • 컴퓨터의 개수 n은 1 이상 200 이하인 자연수입니다.
  • 각 컴퓨터는 0부터 n-1인 정수로 표현합니다.
  • i번 컴퓨터와 j번 컴퓨터가 연결되어 있으면 computers[i][j]를 1로 표현합니다.
  • computer[i][i]는 항상 1입니다.

입출력 예

4.  소스코드

import java.util.*;

class Solution {
    static int network;
	static HashMap<Integer, ArrayList<Integer>> map;
	static boolean[] visited;
	public static int solution(int n, int[][] computers) {
		makeMap(n, computers);
		network = 0;
		visited = new boolean[n];
		for(int computer = 0; computer < n; computer++) {
			if(!visited[computer]) {
				network++;
				dfs(computer);
			}
		}
		return network;
	}
	
	static void makeMap(int n, int[][] computers) {
		map = new HashMap<>();
		for(int computer = 0; computer < n; computer++) map.put(computer, new ArrayList<>());
		for(int c1 = 0; c1 < n; c1++) {
			for(int c2 = 0; c2 < n; c2++) {
				if(c2 == c1) continue;
				if(computers[c1][c2] == 1) map.get(c1).add(c2);
			}
		}
	}
	
	static void dfs(int computer) {
		visited[computer] = true;
		for(int c : map.get(computer)) {
			if(!visited[c]) dfs(c);
		}
	}
}
profile
자바, 웹 개발을 열심히 공부하고 있습니다!

0개의 댓글