[Java] 네트워크

Korangii·2024년 7월 19일

프로그래머스

목록 보기
4/21
post-thumbnail

네트워크 문제

참고 - velog

DFS 사용

class Solution {
	static boolean visit[];

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


        for(int i=0; i<n; i++) {
        		if(visit[i] == false) {
        			answer++;
        			DFS(i, computers, n);
        		}
        }

        return answer;
    } // End of main

	static void DFS(int i, int computers[][], int n) {
		visit[i] = true;	

		for(int j=0; j<n; j++) {
			if(visit[j] == false && computers[i][j] == 1) {
				DFS(j, computers, n);
			}
		}

	} // End of DFS
} // End of class

BFS 사용

import java.util.*;

class Solution {
    	static boolean visit[];
	static Queue<Integer> que = new LinkedList<>();

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

        for(int i=0; i<n; i++) {
        		if(visit[i] == false) {

        			BFS(i, computers, n);
        			answer++;
        		}
        }

        return answer;
    } // End of main

	static void BFS(int i, int computers[][], int n) {
		que.offer(i);
		visit[i] = true;	

		while( !que.isEmpty() ) {
			int value = que.poll();

			for(int j=0; j<n; j++) {
				if(visit[j] == false && computers[value][j] == 1) {
					visit[j] = true;
					que.offer(j);
				}
			}

		}

	} // End of BFS
} // End of class
profile
https://honeypeach.tistory.com/ 로 이전했습니다.

0개의 댓글