• 有权图的Floyed


    public class Floyed {
    
        public final static int UNLIMITED = Integer.MAX_VALUE;
    
        public static int[][] caculate(final int[][] linkedMatrix) {
            int M = linkedMatrix.length;
            int[][] connectTable = linkedMatrix.clone();
            for (int mid = 0; mid < M; mid++) {
                for (int left = 0; left < M; left++) {
                    if (connectTable[left][mid] < UNLIMITED) {
                        for (int right = 0; right < M; right++) {
                            if (connectTable[mid][right] < UNLIMITED) {
                                int newValue = connectTable[left][mid] + connectTable[mid][right];
                                if (newValue < connectTable[left][right]) {
                                    connectTable[left][right] = newValue;
                                }
                            }
                        }
                    }
                }
            }
            return connectTable;
        }
    
        public static void main(String[] args) {
            int[][] linkedMatrix = new int[][]{
                {0, 50, UNLIMITED, 80, UNLIMITED},
                {UNLIMITED, 0, 60, 90, UNLIMITED},
                {UNLIMITED, UNLIMITED, 0, UNLIMITED, 40},
                {UNLIMITED, UNLIMITED, 20, 0, 70},
                {UNLIMITED, 50, UNLIMITED, UNLIMITED, 0}
            };
            int[][] connectTable = Floyed.caculate(linkedMatrix);
            int M = connectTable.length;
            for (int i = 0; i < M; i++) {
                for (int j = 0; j < M; j++) {
                    System.out.print((connectTable[i][j] == UNLIMITED ? "-" : connectTable[i][j]) + "	");
                }
                System.out.println();
            }
    
        }
    }
    

    输出:

    0	50	100	80	140	
    -	0	60	90	100	
    -	90	0	180	40	
    -	110	20	0	60	
    -	50	110	140	0	






  • 相关阅读:
    腾讯安全上海游戏部门笔试题
    2017
    2016
    2015
    2014
    2013
    2012
    2011
    2010
    2009
  • 原文地址:https://www.cnblogs.com/leeeee/p/7276140.html
Copyright © 2020-2023  润新知