最短送餐路程計算, 美團筆試題2020
阿新 • • 發佈:2020-07-12
import java.util.*; public class Main { static int dijkstra(int[][] g, int n, int target, int k, int value){ boolean[] finished = new boolean[n]; int[] distance = new int[n]; Arrays.fill(distance, Integer.MAX_VALUE); distance[0] = k == 0 ? value : 0; if(k != 0) { for(int i=0; i < n; i++) if(i != k && g[k][i] != -1) { g[i][k] = g[k][i] += value; } } for(int i=0; i < n; i++) { int t = -1; for(int j=0; j < n; j++) { if(finished[j]==false &&(t == -1 || distance[t] > distance[j])) { t = j; } } finished[t] = true; for(int j=0; j < n; j++) { if(g[t][j] != -1) { distance[j] = Math.min(distance[j], distance[t]+g[t][j]); } } } return distance[target]; } public static void main(String[] args){ Scanner sc = new Scanner(System.in); int target = sc.nextInt(); int k = sc.nextInt(), value=sc.nextInt(); int n = 6; int[][] g = new int[n][n]; for(int i=0; i < n; i++){ Arrays.fill(g[i], -1); g[i][i] = 0; } g[0][1] = 1; g[0][2] = 2; g[0][3] = 7; g[1][0] = 1; g[1][2] = 2; g[1][4] = 5; g[1][5] = 4; g[2][0] = 2; g[2][1] = 2; g[2][4] = 4; g[2][3] = 4; g[3][0] = 7; g[3][2] = 4; g[3][4] = 6; g[4][1] = 5; g[4][2] = 4; g[4][3] = 6; g[4][5] = 3; g[5][1]=4; g[5][4] = 3; System.out.println(dijkstra(g, n, target, k, value)); } }