Graph 최단거리 - dijkstra, Floyd Warshall, Bellman Ford

ik_13038·2022년 5월 22일
0

최단 거리 알고리즘

  • 다익스트라 알고리즘
    그래프에서 여러 개의 노드가 있을 때, 특정한 노드에서 출발하여 다른 노드로 가는 각각의 최단 경로를 구해주는 알고리즘 (그리디 알고리즘 활용)
  • 플로이드 워셜 알고리즘
    모든 지점에서 다른 모든 지점까지의 최단 경로를 돌아가며 계산
    (지점의 개수가 적을 경우 사용, 바둑판 제작과 유사)
  • 벨만 포드 알고리즘
    매번 모든 간선을 전부 확인, 음수간선도 계산 가능, 시간 복잡도가 큼

💻 코드

1. Dijkstra (개선된 알고리즘 활용)

매번 방문하지 않은 노드 중에서 최단거리가 가장 짧은 노드를 선택

import java.util.*;

class Node3 implements Comparable<Node3> // compareTo 함수 오버라이딩
{
    private int index;
    private int distance;

    public Node3(int index, int distance)
    {
        this.index = index;
        this.distance = distance;
    }

    public int getIndex() {
        return index;
    }

    public int getDistance(){
        return distance;
    }

    @Override
    public int compareTo(Node3 other)
    {
        if (this.distance < other.distance)
            return -1;
            // 기준값이 비교대상보다 작다. (오름차순 정렬)
        else
            return 1;
    }
}

public class graphTestUpgrade {
    public static final int INF = (int) 1e9; // 무한을 의미하는 값으로 10억
    // 노드의 개수(N), 간선의 개수(M), 시작 노드 번호 (Start)
    // 노드의 개수는 최대 100,000개라고 가정
    public static int n, m, start;
    // 각 노드에 연결되어 있는 노드에 대한 정보를 담는 배열
    public static ArrayList<ArrayList<Node3>> graph = new ArrayList<>();
    public static int[] d = new int[100001];

    public static void dijkstra(int start)
    {
        PriorityQueue<Node3> pq = new PriorityQueue<>();
        // 우선순위 큐를 통해 최단거리 짧은 큐를 먼저 꺼냄
        pq.offer(new Node3(start, 0));
        d[start] = 0;

        while (!pq.isEmpty())
        {
            // 가장 최단거리가 짧은 노드에 대한 정보 꺼내기
            Node3 node = pq.poll();
            int dist = node.getDistance();
            int now = node.getIndex();
            // 현재 이미 처리된 적이 있는 노드라면 무시
            if(d[now] < dist) continue;
            // 현재 노드와 연결된 다른 인접한 노드들을 확인
            for (int i = 0; i < graph.get(now).size(); i++)
            {
                int cost = d[now] + graph.get(now).get(i).getDistance();
                if(cost < d[graph.get(now).get(i).getIndex()])
                {
                    d[graph.get(now).get(i).getIndex()] = cost;
                    pq.offer(new Node3(graph.get(now).get(i).getIndex(), cost));
                    // 계산 비용이 더 작다면 그 값을 대입 후 pq에 offer
                }
            }
        }

    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        n = sc.nextInt();
        m = sc.nextInt();
        start = sc.nextInt();

        // 그래프 초기화
        for(int i = 0; i <= n; i++)
            graph.add(new ArrayList<Node3>());
            // 그래프 배열에 해당 기본 정보 대입

        // 모든 간선 불러오기
        for(int i = 0; i < m; i++)
        {
            int a = sc.nextInt();
            int b = sc.nextInt();
            int c = sc.nextInt();

            // a번 노드에서 b번 노드롤 가는데 걸리는 c의 비용
            graph.get(a).add(new Node3(b, c));
        }

        // 최단 거리 테이블을 모두 무한으로 초기화
        Arrays.fill(d, INF);
		// 기본 비용을 최대로 초기화
        
        // 다익스트라 알고리즘을 수행
        dijkstra(start);

        // 모든 노드로 가기 위한 최단 노드를 출력
        for(int i = 1; i <= n; i++)
        {
            // 도달할 수 없는 경우, 무한이라고 출력
            if(d[i] == INF)
                System.out.println("INFINITY");
            else
                System.out.println(d[i]);
        }

    }
}

2. Floyd-Warshall

import java.util.*;

public class Floyd_Warshall
{
    public static final int INF = (int) 1e9; // 무한 == 10억
    // 노드의 개수(N), 간선의 개수(M)
    // 노드의 개수는 최대 500개
    public static int n, m;
    // 2차원 배열(그래프 표현)을 그리기
    public static int[][] graph = new int[501][501];

    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);

        n = sc.nextInt();
        m = sc.nextInt();

        // 최단 거리 테이블을 모두 무한으로 초기화
        for (int i = 0; i < 501; i++)
        {
            Arrays.fill(graph[i], INF);
        }

        // 자기 자신에서 자기 자신으로 가는 비용은 0으로 초기화
        for (int a = 1; a <= n; a++)
        {
            for(int b = 1; b <= n; b++)
            {
                if(a==b) graph[a][b] = 0;
            }
        }

        // 각 간선에 대한 정보를 입력 받아 그 값으로 초기화
        for (int i = 0; i < m; i++)
        {
            // A에서 B로 가는 비용을 C라고 설정
            int a = sc.nextInt();
            int b = sc.nextInt();
            int c = sc.nextInt();;

            graph[a][b] = c;
        }

        // 점화식에 따라 플로이드 워셜 알고리즘을 수행
        for(int k = 1; k <= n; k++)
            for(int a = 1; a <= n; a++)
                for(int b = 1; b <= n; b++)
                {
                    graph[a][b] = Math.min(graph[a][b], graph[a][k] + graph[k][b]);
                }

        // 수행된 결과 출력
        for (int a = 1; a <= n; a++) {
            for (int b = 1; b <= n; b++) {
                // 도달할 수 없는 경우, 무한(INFINITY)이라고 출력
                if (graph[a][b] == INF) {
                    System.out.print("INFINITY ");
                }
                // 도달할 수 있는 경우 거리를 출력
                else {
                    System.out.print(graph[a][b] + " ");
                }
            }
            System.out.println();
        }
    }
}

3. Bellman Ford

벨만 포드는 음수 가중치가 존재하는 경우에도 적용할 수 있으며
시간 복잡도가 O(VE) 입니다. (V: 정점 개수, E: 간선 개수)

profile
글 연습, 정보 수집

0개의 댓글