본문 바로가기

Development/CodingTest

[DFS] 프로그래머스 level 3 네트워크 java 풀이

https://school.programmers.co.kr/learn/courses/30/lessons/43162?language=java

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

문제 풀이

  1. 방문한 컴퓨터를 boolean 배열에 저장해야 함
  2. computers의 각 요소를 순회하면서 자기 자신의 인덱스가 아닌 요소가 1인지 검사
  3. 1이면 그 컴퓨터로 이동 (dfs로 인덱스 전달), boolean 배열에 true로 변경
  4. 순회를 다 했을때 isVisited가 true인 경우 answer++

코드

class Solution {
    public int solution(int n, int[][] computers) {
        int answer = 0;
        boolean[] isVisited = new boolean[n];

        for (int i = 0; i < n; i++) {
            if (!isVisited[i]) {
                dfs(computers, i, isVisited);
                answer++;
            }
        }

        return answer;
    }

    public boolean[] dfs(int[][] computers, int i, boolean[] isVisited) {
        isVisited[i] = true;
        for (int j = 0; j < computers.length; j++) {
            if (i != j && computers[i][j] != 0 && !isVisited[j]) {
                isVisited = dfs(computers, j, isVisited);
            }
        }
        return isVisited;
    }

}