Lv 3. 가장 먼 노드

2024. 10. 9. 14:31·Algorithm & Data Structures/Programers

https://school.programmers.co.kr/learn/courses/30/lessons/49189

 

프로그래머스

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

programmers.co.kr

 

 

 

이번 문제는 Dijkstra 기법을 활용하여 

최단거리를 ans[] 배열에 저장하고

최단 거리중 가장 큰값의 갯수를 세어

반환하는 형식으로 풀이하였다.

 

이차원 배열을 통해 node간의 간선 연결정보를

저장하였더니 메모리 초과가 나타나

 ArrayList를 활용하여 간선 연결된 것만 data 저장을

하는 방식으로 풀어내었다.

 

 

 

// 다익스트라 dijkstra algorithm 최단경로 algorithm
// 반대로 가자.
import java.util.*;

class Solution {
    int[] ans;  //최단거리 저장 
    boolean[] isVisited; //들렀나?
    ArrayList<Integer>[] map; 
    class Node{
        int edge;
        int dis;
        public Node(int edge, int dis){
            this.edge = edge;
            this.dis = dis;
        }
    }
    private void BFS(int n){
        Queue<Node> q = new ArrayDeque<>();
        q.add(new Node(1,0));
        while(!q.isEmpty()){
            Node now = q.poll();
            if(isVisited[now.edge]) continue; // 만약 최단경로아니고 이미들른곳이면 pass
            isVisited[now.edge] = true;
            ans[now.edge] = now.dis;
            for(int i : map[now.edge]){
                if((now.dis+1) < ans[i])
                    q.add(new Node(i,now.dis+1));
            }
        }
    }
    //최대 경로 갯수 몇개 
    private int findAnswer(int n){
        int maxValue = Integer.MIN_VALUE;
        int result = 0;
        for(int i = 1 ; i < n ; i++){
            if(maxValue < ans[i]){
                result = 1;
                maxValue = ans[i];
            }else if( maxValue == ans[i]) result++;
            
        }
        return result;
    }
    public int solution(int n, int[][] edge) {
        ans = new int[n+1];
        isVisited = new boolean[n+1];
        map = new ArrayList[n+1];
        //초기화
        Arrays.fill(ans,Integer.MAX_VALUE);
        for(int i = 1 ; i <= n ; i++)
            map[i] = new ArrayList<>();
        for(int[] connect : edge){
            map[connect[0]].add(connect[1]);
            map[connect[1]].add(connect[0]);
        }
        BFS(n+1);
        return findAnswer(n+1);
    }
}

// 메모리초과 이차원배열을 arraylist로

'Algorithm & Data Structures > Programers' 카테고리의 다른 글

Lv 3. 징검다리 건너기  (0) 2024.10.30
Lv 3. 섬연결하기  (2) 2024.10.28
Lv 2. 행렬의 곱셈  (0) 2024.10.07
Lv 3. 방금 그 곡  (2) 2024.10.06
Lv 3. 보석 쇼핑  (3) 2024.10.05
'Algorithm & Data Structures/Programers' 카테고리의 다른 글
  • Lv 3. 징검다리 건너기
  • Lv 3. 섬연결하기
  • Lv 2. 행렬의 곱셈
  • Lv 3. 방금 그 곡
Geisha
Geisha
개발 일기
  • Geisha
    Geisha
    Geisha
  • 전체
    오늘
    어제
    • 분류 전체보기 (304) N
      • Algorithm & Data Structures (230) N
        • BOJ (89) N
        • SWEA (1)
        • Programers (136)
        • Data Structures (3)
      • DB (21) N
        • SQL (15) N
        • RDBMS (2)
      • Java (1)
        • Class (1)
      • Spring (5)
        • Spring MVC (1)
        • Annotations (1)
      • CS (36)
        • 운영체제 (13)
        • 네트워크 (5)
      • Tool (6)
        • Git (5)
        • AWS (1)
      • Project (1)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    이진탐색
    스택
    경로압축
    후위순회
    DynamicProgramming
    Stack
    백트래킹
    algorithm
    programmers
    이분탐색
    유니온파인드
    PriorityQueue
    BFS
    구현
    위상정렬
    투포인터
    동적계획법
    전위순회
    unionfind
    binarySearch
    백준
    dp
    Dijkstra
    Union-Find
    baekjoon
    다익스트라
    Java
    프로그래머스
    dfs
    알고리즘
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.0
Geisha
Lv 3. 가장 먼 노드
상단으로

티스토리툴바