반응형
https://school.programmers.co.kr/learn/courses/30/lessons/43162
프로그래머스
SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
Review
DFS와 BFS 모두로 풀어보고 싶어서 도전해봤다.
Code
import java.util.*;
class Solution {
boolean[] visited;
public int solution(int n, int[][] computers) {
int answer = 0;
visited = new boolean[n];
for (int i = 0; i < n; i++) {
if (!visited[i]) {
// dfs(i, n, computers);
bfs(i, n, computers);
answer++;
}
}
return answer;
}
private void dfs(int node, int n, int[][] computers) {
visited[node] = true;
for (int i = 0; i < n; i++) {
if (!visited[i] && computers[node][i] == 1) {
dfs(i, n, computers);
}
}
}
private void bfs(int node, int n, int[][] computers) {
Queue<Integer> q = new LinkedList<>();
q.offer(node);
visited[node] = true;
while (!q.isEmpty()) {
int current = q.poll();
for (int i = 0; i < n; i++) {
if (computers[current][i] == 1 && !visited[i]) {
visited[i] = true;
q.offer(i);
}
}
}
}
}반응형
'Dev > Programmers' 카테고리의 다른 글
| [프로그래머스] 단어 변환 (Java) (0) | 2024.12.17 |
|---|---|
| [프로그래머스] 게임 맵 최단거리 (Java) (0) | 2024.12.17 |
| [프로그래머스] 타겟 넘버 (Java) (0) | 2024.12.17 |
| [프로그래머스] H-Index (Java) (2) | 2024.12.16 |
| [프로그래머스] 가장 큰 수 (Java) (0) | 2024.12.16 |