无权图的Warshall算法

Warshall算法 :将无权图的连接矩阵转化为联通表。

 

public class Walshall {

    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] > 0) {
                    for (int right = 0; right < M; right++) {
                        if (connectTable[mid][right] > 0) {
                            connectTable[left][right] = 1;
                        }
                    }
                }
            }
        }
        return connectTable;
    }

    public static void main(String[] args) {
        int[][] linkedMatrix = new int[][]{
            {0, 0, 1, 0, 0},
            {1, 0, 0, 0, 1},
            {0, 0, 0, 0, 0},
            {0, 0, 0, 0, 1},
            {0, 0, 1, 0, 0}
        };
        int[][] connectTable = Walshall.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] + "\t");
            }
            System.out.println();
        }

    }
}

输出:

0	0	1	0	0	
1	0	1	0	1	
0	0	0	0	0	
0	0	1	0	1	
0	0	1	0	0	


posted @ 2015-03-06 14:01  lihui1625  阅读(106)  评论(0编辑  收藏  举报