Java中邻接矩阵的最小生成树

发布于 2024-10-07 12:38:34 字数 598 浏览 0 评论 0原文

请帮助我理解如何从图的邻接矩阵中获取最小生成树! 我用java写了关于它的课程作业,截止日期是2010年12月16日,但我觉得它会失败。 现在我的程序可以:

  1. 绘制节点
  2. 绘制边
  3. 用边的权重在绘图的基础上生成图形的邻接矩阵
  4. 找到连接到节点的最小边
  5. 并具有一些其他测试/测试的功能

但我不知道如何实现 Prim / Kruskal 算法爪哇。我尝试寻找一些解决办法 在谷歌中,但只找到需要运行.obj文件的Java小程序,而且我也无法运行它。

我编写了一些简单的控制台 java pattern ,现在可以生成并打印图形的邻接矩阵。任何人都可以添加返回图的最小生成树的邻接矩阵的函数,如下所示:

public static int[][] mst(int[][] graph, int n) {
    ...
}

其中:

  • 图 - 是在 n 个
  • 顶点(节点)

中生成的图提前致谢!

Please, help me to understand how to get minimal spanning tree from adjacency matrix of graph!
I write coursework about it in java, deadline is 16.12.2010, but I feel that it shall be fail.
Now my program can:

  1. Draw nodes
  2. Draw edges
  3. Generate adjacency matrix of graph on basement of your drawing with weight of edges
  4. Find minimal edge connected to node
  5. and have some other testing / tested features

But I don't know how realize Prim / Kruskal algorhythm in Java. I try to find some resolves
in google, but find only Java-applet, that needs to work .obj files, also I can't run it.

I write some Simple console java pattern that now generate and print adjacency matrix of graph. Can anybody add function that returns adjacency matrix of minimal spanning tree of graph looking like:

public static int[][] mst(int[][] graph, int n) {
    ...
}

where:

  • graph - is generated graph in n
  • amount of vertexes (nodes)

Thanks in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

阳光下的泡沫是彩色的 2024-10-14 12:38:34

鉴于您的程序目前无法处理不相交集数据结构,您可能需要使用 Prim 的。

鉴于您已经可以完成 Prim 所需的大部分操作,我将用伪代码将其提供给您。

int bestDist[N]
int mst[N][N]
int cameHere[N]
bool done[N]
FOR i = 0..N-1:
 bestDist[i] = INFINITY
 done[i] = false
 FOR j=0..N-1:
  mst[i][j] = INFINITY

// start at any node
bestDist[0] = 0;
FOR i = 0..N-1:
 bestNode = INFINITY
 bestNodeDist = INFINITY

 IF bestNode != 0:
  mst[cameHere[bestNode]][bestNode] = graph[cameHere[bestNode]][bestNode]

 // find closest node
 FOR j= 0..N-1:
  IF !done[j] AND bestDist[j] < bestNodeDist:
   bestNode = j
   bestNodeDist = bestNodeDist[j]

 // update surrounding nodes
 FOR j=0..N-1:
  IF !done[j] AND bestNodeDist + graph[bestNode][j] < bestDist[j]:
   bestDist[j] = bestNodeDist + graph[bestNode][j]
   cameHere[j] = bestNode

return mst

这在 O(N^2) 中运行,但您可以使其在 O(E log E) 中运行,其中如果您使用堆,则 E = num 边。

Given your program at the moment can't handle the Disjoint Set Data Structure, you'd probably want to use Prim's.

Seeing that you can already do most of the things required to do Prim's, I'll give it to you in pseudocode.

int bestDist[N]
int mst[N][N]
int cameHere[N]
bool done[N]
FOR i = 0..N-1:
 bestDist[i] = INFINITY
 done[i] = false
 FOR j=0..N-1:
  mst[i][j] = INFINITY

// start at any node
bestDist[0] = 0;
FOR i = 0..N-1:
 bestNode = INFINITY
 bestNodeDist = INFINITY

 IF bestNode != 0:
  mst[cameHere[bestNode]][bestNode] = graph[cameHere[bestNode]][bestNode]

 // find closest node
 FOR j= 0..N-1:
  IF !done[j] AND bestDist[j] < bestNodeDist:
   bestNode = j
   bestNodeDist = bestNodeDist[j]

 // update surrounding nodes
 FOR j=0..N-1:
  IF !done[j] AND bestNodeDist + graph[bestNode][j] < bestDist[j]:
   bestDist[j] = bestNodeDist + graph[bestNode][j]
   cameHere[j] = bestNode

return mst

This runs in O(N^2) but you can make it run in O(E log E), where E = num edges if you uses a heap.

年华零落成诗 2024-10-14 12:38:34

如果有人正在寻找带有邻接矩阵实现的 MST,可以参考我的 Java 示例代码。我发布它是因为 Junkbot 答案缺乏一些细节。它的运行时间为 O(n^2),因此 Prim 的算法是用于查找 MST 的密集/完整图的最佳选择。

    public void MST-Prim()
    {
    int[] source = new int[numberOfVertices]; // i-th element contains number of source vertex for the edge with the lowest cost from tree T to vertex i
    double[] dist = new double[numberOfVertices]; //i-th element contains weight of minimal edge connecting i with source[i] 
    indicators = new boolean[numberOfVertices];  //if true, vertex i is in tree T

    // Mark all vertices as NOT being in the minimum spanning tree
    for (int i = 0; i < numberOfVertices; i++)
    {
        indicators[i] = false;
        dist[i] = Double.POSITIVE_INFINITY;
    }

     //we start with vertex number 0
    indicators[0] = true;
    dist[0] = 0;
    int bestNeighbour = 0;// lastly added vertex to the tree T 
    double minDist; 

    for (int i = 0; i < numberOfVertices - 1; i++)
    {
        minDist = Double.POSITIVE_INFINITY;

        for (int j = 0; j < numberOfVertices; j++) // fill dist[] based on distance to bestNeighbour vertex
        {
            if (!indicators[j])
            {
                double weight = fullGraph.getEdgeWeight(bestNeighbour, j);

                if (weight < dist[j])
                {
                    source[j] = bestNeighbour;
                    dist[j] = weight;
                }
            }
        }

        for (int j = 0; j < numberOfVertices; j++) // find index of min in dist[]
        {
            if (!indicators[j])
            {
                if (dist[j] < minDist)
                {
                    bestNeighbour = j;
                    minDist = dist[j];
                }
            }
        }

        if (bestNeighbour != 0)
        {//add the edge (bestNeighbour, dist[bestNeighbour]) to tree T
            addEdgeToTree(new GraphEdge(fullGraph.getNode(source[bestNeighbour]), fullGraph.getNode(bestNeighbour),
                    dist[bestNeighbour]));
            indicators[bestNeighbour] = true;
        }

    }

}

If anyone is looking for MST with adjacency matrix implementation there's my sample code in Java. I post it because Junkbot answer lacks some details. It runs in O(n^2) so Prim's algorithm is the best choice for dense / full graph for finding MST.

    public void MST-Prim()
    {
    int[] source = new int[numberOfVertices]; // i-th element contains number of source vertex for the edge with the lowest cost from tree T to vertex i
    double[] dist = new double[numberOfVertices]; //i-th element contains weight of minimal edge connecting i with source[i] 
    indicators = new boolean[numberOfVertices];  //if true, vertex i is in tree T

    // Mark all vertices as NOT being in the minimum spanning tree
    for (int i = 0; i < numberOfVertices; i++)
    {
        indicators[i] = false;
        dist[i] = Double.POSITIVE_INFINITY;
    }

     //we start with vertex number 0
    indicators[0] = true;
    dist[0] = 0;
    int bestNeighbour = 0;// lastly added vertex to the tree T 
    double minDist; 

    for (int i = 0; i < numberOfVertices - 1; i++)
    {
        minDist = Double.POSITIVE_INFINITY;

        for (int j = 0; j < numberOfVertices; j++) // fill dist[] based on distance to bestNeighbour vertex
        {
            if (!indicators[j])
            {
                double weight = fullGraph.getEdgeWeight(bestNeighbour, j);

                if (weight < dist[j])
                {
                    source[j] = bestNeighbour;
                    dist[j] = weight;
                }
            }
        }

        for (int j = 0; j < numberOfVertices; j++) // find index of min in dist[]
        {
            if (!indicators[j])
            {
                if (dist[j] < minDist)
                {
                    bestNeighbour = j;
                    minDist = dist[j];
                }
            }
        }

        if (bestNeighbour != 0)
        {//add the edge (bestNeighbour, dist[bestNeighbour]) to tree T
            addEdgeToTree(new GraphEdge(fullGraph.getNode(source[bestNeighbour]), fullGraph.getNode(bestNeighbour),
                    dist[bestNeighbour]));
            indicators[bestNeighbour] = true;
        }

    }

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文