Shortest Path

Floyd Warshall

Link

  • 尋找點對點之間的最短距離

  • 更新v次edge的情況

  • Time O(n^3)

package graph;
import com.sun.tools.doclets.formats.html.SourceToHTMLConverter;

import java.util.*;

public class floyd_warshall {
    private void fw(int v, int[][] edges){
        int inf = (int)1e8;

        // init distance matrix
        int[][] matrix = new int[v][v];
        for(int i=0; i<v; i++){
            for(int j=0; j<v; j++){
                if(i==j) matrix[i][j]=0;
                else matrix[i][j] = inf;
            }
        }

        // read the edge to matrix
        for(int[] e: edges){
            matrix[e[0]][e[1]] = e[2];
        }

        // Floyd Warshall Algo
        for(int k=0; k<v; k++){
            for(int i=0; i<v; i++){
                for(int j=0; j<v; j++){
                    if(matrix[i][j] > matrix[i][k] + matrix[k][j]){
                        matrix[i][j] = matrix[i][k] + matrix[k][j];
                    }
                }
            }
        }

        // print matrix
        StringBuilder sb = new StringBuilder();
        for(int[] row: matrix){
            for(int n: row){
                sb.append(n).append(",");
            }
            sb.append("\n");
        }

        System.out.println(sb.toString());
    }

    public static void main(String[] args) {
        floyd_warshall f = new floyd_warshall();
        int[][] e = new int[][]{
                {0,1,2},
                {0,2,6},
                {0,3,4},
                {1,2,3},
                {2,0,7},
                {2,3,1},
                {3,0,5},
                {3,2,12}
        };

        f.fw(4, e);
    }
}

Dijkstra

Link

  • Greedy, 每次尋找neighbor dist最短的vertex

  • weight不能是負數

  • Time O(E + VlogV)

  • A visited set, a minHeap<[node][distance to start]>

  • Heap會優先更新距離短的,使vertex 更新必定是最短距離

787. Cheapest Flights Within K Stops

There are n cities connected by m flights. Each fight starts from city u and arrives at v with a price w.

Now given all the cities and fights, together with starting city src and the destination dst, your task is to find the cheapest price from src to dst with up to k stops. If there is no such route, output -1.

  • maintain cost and stop array

  • 遇到 dst 即退出

  • 遇到 stop >= K+1 即拋棄 continue

  • update cost[v] if curCost + matrix[u][v] is less

  • update stop[v] if stop+1 is less

  • return cost[v] and check if valid

1102. Path With Maximum Minimum Value

Given a matrix of integers A with R rows and C columns, find the maximum score of a path starting at [0,0] and ending at [R-1,C-1].

The score of a path is the minimum value in that path. For example, the value of the path 8 → 4 → 5 → 9 is 4.

Explain

  1. Local Greedy, 從四個方向找到 local min然後從maxHeap選擇max延伸

778. Swim in Rising Water

Last updated

Was this helpful?