팡세영
Log sey
팡세영
전체 방문자
오늘
어제
  • 분류 전체보기 (76) N
    • PS (45)
      • programmers (13)
      • 백준 (29)
    • Android (16)
    • Daily (0)
    • Kotlin (6)
    • Design Pattern (3) N
    • Java (1)
    • Flutter (1)
    • 책 리뷰 (1) N
      • 클린 아키텍처 (1) N

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • 해쉬맵
  • 클린아키텍처
  • 자바
  • programmers #프로그래머스
  • 프로그래머스
  • binding
  • DFS
  • BFS
  • mvvm
  • ArcitecturePattern
  • flutter
  • 실버
  • 안드로이드
  • 정렬
  • compose
  • 문자열
  • 골드
  • LEVEL2
  • Android
  • programmers
  • 백준
  • 단일책임원칙
  • TestCode
  • CustomView
  • 하단네비게이션바
  • java
  • 완전탐색
  • Kotlin
  • 구현
  • 의존성 주입

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
팡세영

Log sey

백준 1753 - 최단 경로 (다익스트라)
PS/백준

백준 1753 - 최단 경로 (다익스트라)

2022. 9. 20. 08:47


[문제 해결]

  • 다익스트라를 이용한 최단경로 문제이다.
  • 방문하지 않은 노드 중에서 가장 비용이 적은 노드를 선택한다
  • 해당 노드로부터 갈 수 있는 노드들의 비용을 갱신한다

[Java]

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;

public class Main {

    private static boolean visited [];
    private static int dist[];
    private static ArrayList<ArrayList<Node>> graph = new ArrayList<>();
    private static int v,e, start;

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());

        initGraph(br,st);
        dijkstra();
        print();


    }

    private static void initGraph(BufferedReader br, StringTokenizer st) throws IOException {
        v = Integer.parseInt(st.nextToken());   // 정점의 개수
        e = Integer.parseInt(st.nextToken());   // 간선의 개수

        visited = new boolean[v+1];
        dist = new int[v+1];
        Arrays.fill(dist,Integer.MAX_VALUE);

        for(int i=0; i<=v; i++) graph.add(new ArrayList<>());

        start = Integer.parseInt(br.readLine());
        dist[start] = 0;
        for(int i=0; i<e; i++){
            st = new StringTokenizer(br.readLine());
            int stNode = Integer.parseInt(st.nextToken());
            int edNode = Integer.parseInt(st.nextToken());
            int cost = Integer.parseInt(st.nextToken());

            graph.get(stNode).add(new Node(edNode, cost));
        }
    }

    private static void dijkstra(){
        for(int i=0; i<v; i++){
            int curCost = Integer.MAX_VALUE;
            int curIdx = 0;

            // 방문하지 않은 노드중 최소 값 찾기
            for(int j=1; j<v+1; j++){
                if(!visited[j] && dist[j] < curCost){
                    curCost = dist[j];
                    curIdx = j;
                }
            }

            visited[curIdx] = true;

            for(int j=0; j< graph.get(curIdx).size(); j++){
                Node node = graph.get(curIdx).get(j);

                dist[node.idx] = Math.min(dist[node.idx], dist[curIdx] + node.cost);
            }
        }
    }

    private static void print(){
        for(int i=1; i<=v; i++){
            if(dist[i] == Integer.MAX_VALUE) System.out.println("INF");
            else System.out.println(dist[i]);
        }
    }
}

class Node{
    int idx;
    int cost;

    Node(int idx, int cost){
        this.idx = idx;
        this.cost = cost;
    }
}

'PS > 백준' 카테고리의 다른 글

[백준] - 키 큰 사람 11292  (0) 2022.11.07
[백준] - 자리배정 10157  (0) 2022.11.06
백준 안전영역 2468 - java  (0) 2022.08.26
알고리즘 수업 - 깊이 우선 탐색  (0) 2022.08.19
백준 - 점프왕 쩰리 (Small) - Java  (0) 2022.08.19
    'PS/백준' 카테고리의 다른 글
    • [백준] - 키 큰 사람 11292
    • [백준] - 자리배정 10157
    • 백준 안전영역 2468 - java
    • 알고리즘 수업 - 깊이 우선 탐색
    팡세영
    팡세영
    Android, CS, PS

    티스토리툴바