[프로그래머스 Lv.3] 네트워크(DFS/BFS)
파이썬 풀이
def dfs(i, computers, visited):
visited[i] = True
for j in range(len(computers[0])):
if computers[i][j] == 1:
computers[i][j] = 0
if not visited[j]:
dfs(j, computers, visited)
def solution(n, computers):
answer = 0
visited = [False] * n
for i in range(len(computers)):
for j in range(len(computers[0])):
if computers[i][j] == 1:
dfs(i, computers, visited)
answer += 1
return answer
자바 풀이
class Solution {
public void dfs(int i, int[][] computers, int[] visited){
visited[i] = 1;
for(int j = 0; j < computers[0].length; j++){
if(computers[i][j] == 1){
computers[i][j] = 0;
if(visited[j] == 0){
dfs(j, computers, visited);
}
}
}
}
public int solution(int n, int[][] computers) {
int answer = 0;
int[] visited = new int[n];
for(int i = 0; i < n; i++){
visited[i] = 0;
}
for(int i = 0; i < computers.length; i++){
for(int j = 0; j < computers[0].length; j++){
if(computers[i][j] == 1){
dfs(i, computers, visited);
answer += 1;
}
}
}
return answer;
}
}