[Java] 네트워크(DFS, 스택)

2024. 3. 23. 12:49·Coding Test/programmers
728x90

2023.07.05 - [Coding Test/programmers] - 네트워크 (BFS)

 

네트워크 (BFS)

def solution(n, computers): answer = 0 visited=[False]*n def BFS(v): queue=[] visited[v]=True queue.append(v) while queue: now=queue.pop(0) visited[now]=True for i in range(n): if i!=now and not visited[i] and computers[now][i]==1: queue.append(i) for x in

karla.tistory.com

 

import java.util.*;

class Solution {
    public int solution(int n, int[][] computers) {
        
        // DFS
   
        boolean[] isVisited = new boolean[n];
        int answer = 0;
        
        for (int i=0; i<n; i++){
            if(isVisited[i]) continue;
            visitAll(i, computers, isVisited);
            answer++;
        }
        
        return answer;
    }
    
    private void visitAll(int computer, int[][] computers, boolean[] isVisited){
        Stack<Integer> stack = new Stack<>();
        stack.push(computer);
        
        while(!stack.isEmpty()){
            int c = stack.pop();
            
            if (isVisited[c]) continue;
            isVisited[c]=true;
            
            for (int next=0; next<computers[c].length; next++) {
                if(computers[c][next]==0) continue;
                stack.push(next);
                
            }
            
        }
    }
}
728x90
'Coding Test/programmers' 카테고리의 다른 글
  • [Java] 다리를 지나는 트럭 (큐)
  • [Java] 기능 개발 (큐)
  • [Java] 카펫(완전탐색)
  • [Java, Python] 거리두기 확인하기 (2차원배열, 좌표)
Karla Ko
Karla Ko
𝘾𝙤𝙣𝙩𝙞𝙣𝙪𝙤𝙪𝙨𝙡𝙮 𝙄𝙢𝙥𝙧𝙤𝙫𝙞𝙣𝙜, 𝘾𝙤𝙣𝙨𝙩𝙖𝙣𝙩𝙡𝙮 𝘿𝙚𝙫𝙚𝙡𝙤𝙥𝙞𝙣𝙜 𝙔𝙚𝙨!
    250x250
  • Karla Ko
    karlaLog
    Karla Ko
  • 전체
    오늘
    어제
    • Total (467)
      • Spring (19)
      • JPA (4)
      • Cloud & Architecture (15)
        • Kubernetes (5)
        • Docker (3)
        • MSA (2)
        • GCP (1)
        • AWS (4)
      • Devops (1)
      • Message Queue (4)
        • Kafka (2)
        • RabbitMQ (2)
      • Git (4)
      • DB (4)
      • Java (9)
      • Python (4)
      • CS (11)
        • OS (8)
        • Network (2)
        • Algorithm (1)
      • Coding Test (392)
        • programmers (156)
        • Graph (43)
        • DP (37)
        • Search (31)
        • Tree (13)
        • Data Structure (26)
        • Combination (12)
        • Implement (18)
        • Geedy (23)
        • Sort (7)
        • Math (21)
        • geometry (2)
  • 블로그 메뉴

    • 홈
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    동적계획법
    힙
    BFS
    프로그래머스
    파이썬
    조합
    스택
    그리디
    LIS
    플로이드워셜
    최단거리
    큐
    DP
    Algorithm
    트리
    월간코드챌린지
    구간합
    이분탐색
    구현
    정렬
    덱
    그래프
    알고리즘
    최소신장트리
    자료구조
    최대공약수
    DFS
    다익스트라
    재귀
    백준
  • hELLO· Designed By정상우.v4.10.3
Karla Ko
[Java] 네트워크(DFS, 스택)
상단으로

티스토리툴바