图的最小生成树2

要用n-1条边将n个顶点连接起来,那么每个顶点都必须至少有一条边与它相连。我们可以随便选择一个顶点开始,找出它的最短的边。例如1号顶点有2条边(1-2,1-3)在这两条边中我们选择一条最短的边(1-2),此时我们认为1号顶点和2号顶点已经连通,我们接着在1号顶点和2号顶点的边中找出最短的边(1-3),此时1,2,3号顶点已经连通,以此类推我们可以将整个图连通

int[][] arrs = new int[6][6];
int[] dis = new int[6];
int[] book = new int[6];

private void initArrs() {
    for (int i = 0; i <= 5; i++) {
        for (int j = 0; j <= 5; j++) {
            if (i == j) {
                arrs[i][j] = 0;
            } else {
                arrs[i][j] = 999;
            }
        }
    }

    arrs[1][3] = 11;
    arrs[3][1] = 11;

    arrs[2][4] = 13;
    arrs[4][2] = 13;

    arrs[3][5] = 3;
    arrs[5][3] = 3;

    arrs[4][5] = 4;
    arrs[5][4] = 4;

    arrs[1][2] = 6;
    arrs[2][1] = 6;

    arrs[3][4] = 7;
    arrs[4][3] = 7;

    arrs[0][1] = 1;
    arrs[1][0] = 1;

    arrs[2][3] = 9;
    arrs[3][2] = 9;

    arrs[0][2] = 2;
    arrs[2][0] = 2;

    for (int i = 0; i <= 5; i++) {
        dis[i] = arrs[0][i];
    }
}

@Test
public void testSmallTree() {
    initArrs();

    int sum = 0, count = 0;
    book[0] = 1;

    while (count < 5) {
        int min = 999;
        int j = -1;

        for (int i = 0; i <= 5; i++) {
            if (dis[i] < min && book[i] == 0) {
                min = dis[i];
                j = i;
            }
        }

        sum += dis[j];
        count++;
        book[j] = 1;

        for (int i = 0; i <= 5; i++) {
            if (dis[i] > arrs[j][i] && book[i] == 0) {
                dis[i] = arrs[j][i];
            }
        }
    }

    System.out.println(sum);
}
posted @ 2017-12-10 17:56  Arthur_08320  阅读(134)  评论(0编辑  收藏  举报