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

2024. 11. 28. 13:42·코테/Algorithm
728x90
 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

 

풀이

 

1. 문제 풀이 아이디어

배열에 ArrayList넣어서 각 노드별로 연결되어있는 노드들의 목록을 만들었다(이중포문 전체를 돌지 않아도 되어 효율적이라 생각했음) 처음 문제를 보자마자 덩어리가 몇 개인지 구해야하기 때문에 DFS로 문제를 해결했다. BFS로도 풀 수 있다고 들어 BFS로도 문제를 풀어봤음.

 

2. 배열에 ArrayList 넣는 법

// ArrayList를 배열로 생성
ArrayList<Integer>[] arr = new ArrayList[N+1];

// 각 배열마다 ArrayList 생성
for(int i=0;i<=N;i++){
	arr[i] = new ArrayList<>();
}

// 배열에 값 넣는 방법
for(int i=0;i<M;i++){
	st = new StringTokenizer(br.readLine());
	int A = Integer.parseInt(st.nextToken());
	int B = Integer.parseInt(st.nextToken());
	arr[B].add(A);
}

출처: https://abcodef.tistory.com/25 [abc의 다락방:티스토리]

 

 

3. 다른 사람들은 어떻게 풀었는가

class Solution {
    public int solution(int n, int[][] computers) {
        int answer = 0;
        boolean[] chk = new boolean[n];
        for(int i = 0; i < n; i++) {
            if(!chk[i]) {
                dfs(computers, chk, i);
                answer++;
            }
        }
        return answer;
    }
    void dfs(int[][] computers, boolean[] chk, int start) {
        chk[start] = true;
        for(int i = 0; i < computers.length; i++) {
            if(computers[start][i] == 1 && !chk[i]) {
                dfs(computers, chk, i);
            }
        }
    }
}

 

내가 생각한 것처럼 방문해야할 노드만 찾아준 것이 dfs내의 코드인 것 같다.

0에서 n까지의 노드중 방문하지 않은 경우, for문을 돌면서 다음 방문해야할 노드(아직 방문하지 않은)를 찾아다닌다.

 

 

전체코드

 

DFS풀이

import java.io.*;
import java.util.*;

class Solution {
    static ArrayList<Integer>[] network;
    static boolean[] visited;
    static int answer = 0;
    public int solution(int n, int[][] computers) {
        network = new ArrayList[computers.length];
        visited = new boolean[computers.length];
        
        //각 컴퓨터와 연결되어 있는 컴퓨터 목록을 network에 넣기
        for(int i=0; i<computers.length; i++){
            network[i] = new ArrayList<>();
            for(int j=0; j<computers[i].length; j++){
                if(computers[i][j] == 1){
                    network[i].add(j);
                }
            }
        }
        
        for(int i=0; i<computers.length; i++){
            if(!visited[i]){
                visited[i] = true;
                DFS(i);
                answer++;
            }
        }
        return answer;
    }
    static void DFS(int node){
        for(int i=0; i<network[node].size(); i++){
            int next = network[node].get(i);
            if(!visited[next]){
                visited[next] = true;
                DFS(next);
            }else{
                continue;
            }
        }
    }
}

 

BFS풀이

import java.io.*;
import java.util.*;

class Solution {
    static ArrayList<Integer>[] network;
    static boolean[] visited;
    static int answer = 0;
    public int solution(int n, int[][] computers) {
        network = new ArrayList[computers.length];
        visited = new boolean[computers.length];
        
        //각 컴퓨터와 연결되어 있는 컴퓨터 목록을 network에 넣기
        for(int i=0; i<computers.length; i++){
            network[i] = new ArrayList<>();
            for(int j=0; j<computers[i].length; j++){
                if(computers[i][j] == 1){
                    network[i].add(j);
                }
            }
        }
        
        for(int i=0; i<computers.length; i++){
            if(!visited[i]){
                visited[i] = true;
                BFS(i);
                answer++;
            }
        }
        return answer;
    }
    
    static void BFS(int node){
        Queue<Integer> q = new LinkedList<>();
        q.offer(node);
        
        while(!q.isEmpty()){
            int now = q.poll();
            for(int i=0; i<network[now].size(); i++){
                int next = network[now].get(i);
                if(!visited[next]){
                    visited[next] = true;
                    q.offer(next);
                }
            }
        }
    }
}

728x90

'코테 > Algorithm' 카테고리의 다른 글

[프로그래머스] N-Queen (JAVA)  (1) 2024.12.09
[프로그래머스] 배달 (JAVA)  (0) 2024.12.04
[프로그래머스] 타겟 넘버 (JAVA)  (1) 2024.11.27
[프로그래머스] 올바른 괄호 (JAVA)  (0) 2024.11.26
[프로그래머스] 기능개발 (JAVA)  (0) 2024.11.26
'코테/Algorithm' 카테고리의 다른 글
  • [프로그래머스] N-Queen (JAVA)
  • [프로그래머스] 배달 (JAVA)
  • [프로그래머스] 타겟 넘버 (JAVA)
  • [프로그래머스] 올바른 괄호 (JAVA)
DROPDEW
DROPDEW
💻 Developer | 기록하지 않으면 존재하지 않는다
  • DROPDEW
    제 2장 1막
    DROPDEW
  • 전체
    오늘
    어제
    • Dev (410) N
      • App·Android (1)
      • BE (42) N
        • HTTP 웹 기본 지식 (8)
        • 스프링 입문 - 코드로 배우는 스프링 부트, 웹 .. (12)
        • 스프링부트와 JPA 활용 (9) N
        • 스프링부트 시큐리티 & JWT (0)
        • PHP (6)
      • FE·Client (23)
        • HTML (1)
        • React (19)
        • Unity (1)
      • Data (12)
        • AI (4)
        • Bigdata (6)
        • Database (1)
        • 빅데이터분석기사 (0)
      • Infra (0)
      • Activity (0)
        • Education (0)
        • Intern (0)
        • 리모트 인턴십 6기 (0)
        • 구름톤 유니브 4기 (0)
        • SW교육기부단 15기 (0)
      • CS (8) N
      • 취준 (13)
        • 자격증 (4)
        • 인적성·NCS (6)
        • 코테·필기·면접 후기 (3)
      • 코테 (270)
        • Algorithm (222)
        • SQL (35)
        • 정리 (13)
      • 인사이트 (27)
        • 회고 (0)
        • 금융경제뉴스 (7)
        • 금융용어·지식 (2)
        • 북마크 (7)
  • 블로그 메뉴

    • 홈
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    다이나믹프로그래밍
    오블완
    누적합
    너비우선탐색
    투포인터
    정렬
    백준
    그래프이론
    그리디알고리즘
    티스토리챌린지
    자료구조
    수학
    시뮬레이션
    문자열
    최단경로
    그래프탐색
    브루트포스 알고리즘
    매개변수탐색
    구현
    이분탐색
  • 최근 댓글

  • 최근 글

  • 250x250
  • hELLO· Designed By정상우.v4.10.3
DROPDEW
[프로그래머스] 네트워크 (JAVA)
상단으로

티스토리툴바