-4
与えられた無向グラフの最小スパニングツリーを見つけるために、PrimとKruskalのアルゴリズムをJavaで実装する必要があります。どうやってやるの ?実装は少なくともPrimのアルゴリズムではO(2)、KruskalのアルゴリズムではO(3)(nはノードの数)を達成する必要があります。ここでJavaのPrimとKruskalアルゴリズム
public class Graph {
/*The following square matrix represents a weighted undirected graph.
the value in (i,j) position indicates the cost between i and j node.
Zeros indicate no connection*/
static int[][] matrix = { { 0, 3, 0, 2, 0, 0, 0, 0, 4 }, // 0
{ 3, 0, 0, 0, 0, 0, 0, 4, 0 }, // 1
{ 0, 0, 0, 6, 0, 1, 0, 2, 0 }, // 2
{ 2, 0, 6, 0, 1, 0, 0, 0, 0 }, // 3
{ 0, 0, 0, 1, 0, 0, 0, 0, 8 }, // 4
{ 0, 0, 1, 0, 0, 0, 8, 0, 0 }, // 5
{ 0, 0, 0, 0, 0, 8, 0, 0, 0 }, // 6
{ 0, 4, 2, 0, 0, 0, 0, 0, 0 }, // 7
{ 4, 0, 0, 0, 8, 0, 0, 0, 0 } // 8
};
/* static int[][] matrix = { { 0, 2, 3, 0, 0 }, // 0
{ 2, 0, 15, 2, 0 }, // 1
{ 3, 15, 0, 0, 13}, // 2
{ 0, 2, 0, 0, 9}, // 3
{ 0, 0, 13, 9, 0}, // 4 }; */
static int Node = matrix.length;
static int[][] Edge = new int[Node][Node];
static int NotConnected = 999999;
public static void MakeGraph() {
for (int i = 0; i < Node; i++) {
for (int j = 0; j < Node; j++) {
Edge[i][j] = matrix[i][j];
if (Edge[i][j] == 0)// If Node i and Node j are not connected
Edge[i][j] = NotConnected;
}
}
// Print the graph representation matrix.
for (int i = 0; i < Node; i++) {
for (int j = 0; j < Node; j++)
if (Edge[i][j] != NotConnected)
System.out.print(" " + Edge[i][j] + " ");
else // when there is no connection
System.out.print(" * ");
System.out.println();
}
}
public static void Prim(){
System.out.println("OUPUT OF PRIM'S ALGORITHM:");
// Write the code for Prim algorithm to find the minimum cost spanning tree here
// and print the result in console with the following format:
/*==========================OUTPUT FORMAT===========================
Minimun Cost of Spanning Tree = "....... "
Edges of the minimum cost spanning tree:
".........................................................."
(for example:
Edges of the minimum cost spanning tree:
"0 -- 1
7 -- 2
0 -- 3
3 -- 4
2 -- 5
5 -- 6
1 -- 7
0 -- 8)"
================================================================== */
}
public static void Kruskal(){
System.out.println("OUPUT OF KRUSKAL'S ALGORITHM:");
// Write the code for Kruskal algorithm to find the minimum cost spanning tree here
// and print the result in console with the following format:
/*==========================OUTPUT FORMAT===========================
Minimun Cost of Spanning Tree = "....... "
Edges of the minimum cost spanning tree:
".........................................................."
================================================================== */
}
public static void main(String[] args) {
MakeGraph();
Prim();
Kruskal();
}
}
だからあなたの特定の問題は何ですか? – avysk