[프로그래머스 Lv.3] 네트워크(DFS/BFS)

shin·2022년 11월 24일
0

CodingTest 문제 풀이

목록 보기
75/79

[프로그래머스 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 # 해당 자리를 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;
    }
}
profile
Backend development

0개의 댓글