문제 풀이/프로그래머스

[프로그래머스] 네트워크(JAVA)

27200 2024. 5. 4. 22:02

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


풀이

class Solution {
    public int solution(int n, int[][] computers) {
        int answer = 0;
        boolean[][] visited = new boolean[n][n];
        for(int i = 0; i < n; i++){
            for(int j = 0; j < n; j++){
                if(computers[i][j] == 1 && !visited[i][j]){
                    dfs(i, j, visited, computers);
                    answer++;
                }
            }
        }
        return answer;
    }

    public static void dfs(int i, int j, boolean visited[][], int[][] computers){
        visited[i][j] = true;
        for(int k = 0; k < computers.length; k++){
            if(computers[j][k] == 1 && !visited[j][k]){
                dfs(j, k, visited, computers);
            }
        }
    }
}

dfs를 이용해 간단하게 answer++만 처리해주는 방식으로 진행하였다.