‡ CODING TEST STUDY ‡/º 백준

[프로그래머스 | Java Lv.3] [복습] 네트워크 (dfs/bfs)

Trudy | 송연 2024. 6. 13. 17:09

문제

https://school.programmers.co.kr/learn/courses/30/parts/12421

 

프로그래머스

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

programmers.co.kr


간단하게 생각하면 됐는데 상하좌우를 갑자기 생각해서 어렵게 가다가 잘못된 걸 알고 다시 돌아왔던.. 

bfs로만 풀리는 문제도 있으니까 bfs로도 풀어보자 다음 문제부터는...!

 

최종 코드

package week6.baek.dfsbfs;

public class Network {
    static boolean[] visited;
    public static void dfs(int[][] computers, int x){
        visited[x] = true;

        for (int i = 0; i < computers.length; i++) {
            if(computers[x][i] == 1 && !visited[i]) {
                dfs(computers, i);
            }
        }

    }
    public static int solution(int n, int[][] computers) {
        visited = new boolean[computers.length];

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

        return count;
    }

    public static void main(String[] args) {
        int[][] computers = {{1,1,0}, {1,1 ,0}, {0,0,1}};
        System.out.println(solution(3, computers));
    }
}