public class LowestCost{//不可达记为INF//不可记为Integer.MAX_VALUE,再加cost会变成负数,影响结果final static int INF = 999999;//下标与名称的映射static Map<Integer,String> map = new HashMap<>();//用二位数组邻接矩阵表示有向加权图,下标表示边,值表示权//以行为边的起点,列为边的终点//INF表示不可达static int[][] graph = {{INF,6,2,INF},{INF,INF,INF,1},{INF,3,INF,5},{INF,INF,INF,INF}};static int[] costs = {INF, //start6, //A2, //BINF //end};static int[] parents = {INF, //start 的起点0, //A的起点0, //B的起点-1 //end的起点};//记录是否处理过,处理过 记为1static int[] proceessed = {0,0,0,0};public static void main(String[] args) {map.put(0,"start");map.put(1,"A");map.put(2,"B");map.put(3,"end");int node = findLowestCostNode(costs);while (node != 0) {int cost = costs[node];for (int i = 0; i < graph[node].length; i++) {int newCost = cost + graph[node][i];if (costs[i] > newCost){costs[i] = newCost;parents[i] = node;}}proceessed[node] = 1;node = findLowestCostNode(costs);}//最终输出parents表,即可得出花费最少路线for (int i = 0; i < parents.length; i++) {System.out.print(map.get(i)+" ");System.out.println(map.get(parents[i]));}}//返回花费最少的节点(下标)public static int findLowestCostNode(int[] costs) {int lowCost = Integer.MAX_VALUE;int lowCostNode = 0;for (int i = 0; i < costs.length; i++) {int cost = costs[i];if (cost < lowCost && proceessed[i] == 0) {lowCost = cost;lowCostNode = i;}}return lowCostNode;}}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。