문제
https://school.programmers.co.kr/learn/courses/30/lessons/43162
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
최종 코드
package week3.baek.dfsbfs;
public class Ex2 {
static int[] visited;
public void dfs(int i, int[][] computers){
visited[i] = 1;
for (int j = 0; j < computers.length; j++) {
if(computers[i][j] == 1 && visited[j] == 0){
dfs(j, computers);
}
}
}
public int solution(int n, int[][] computers) {
int answer = 0;
visited = new int[n];
for (int i = 0; i < computers.length; i++) {
if(visited[i] == 0){
answer++;
dfs(i, computers);
}
}
return answer;
}
}
class Ex2Main{
public static void main(String[] args) {
int n = 3;
// 110
// 110
// 001
// 110
// 111
// 011
int[][] computers ={{1, 1, 0}, {1, 1, 0}, {0, 0, 1}};
int[][] computers2 ={{1, 1, 0}, {1, 1, 1}, {0, 1, 1}};
Ex2 ex2 = new Ex2();
System.out.println(ex2.solution(n, computers));
System.out.println(ex2.solution(n, computers2));
}
}
참고
'‡ CODING TEST STUDY ‡ > º 프로그래머스' 카테고리의 다른 글
[프로그래머스 | Java Lv.2] 모음사전 (0) | 2024.05.18 |
---|---|
[프로그래머스 | Java Lv.3] 여행 경로 (0) | 2024.05.16 |
[프로그래머스 | Java Lv.2] 타겟 넘버 (0) | 2024.05.15 |
[프로그래머스 | Java Lv.1] 최소직사각형 (0) | 2024.05.15 |
[프로그래머스 | Java Lv.3] 이중우선순위큐 (0) | 2024.05.15 |