我正在为Java学校开展一个项目。我们正在编写胡树的算法。我编写了一个递归方法来设置每个节点的级别取决于邻接矩阵。当我运行代码时,我收到堆栈溢出错误。
我的完整代码如下。我遇到了level()方法的问题。请帮忙
package husalgo;
import java.util.Arrays;
import javax.swing.JOptionPane;
public class HusAlgo
{
private static int numJobs;
public static void main(String[] args)
{
input();
}
public static void input()
{
int level = 0;
int root = 0;
numJobs = Integer.parseInt(JOptionPane.showInputDialog(null, "Please enter number of jobs: "));
int machines = Integer.parseInt(JOptionPane.showInputDialog(null, "Please enter number of machines: "));
int[] begin = new int[numJobs];
int[] end = new int[numJobs];
for (int i = 0; i < numJobs - 1; i++)
{
begin[i] = Integer.parseInt(JOptionPane.showInputDialog(null, "Please enter the begining arc for job " + (i + 1) + ": "));
end[i] = Integer.parseInt(JOptionPane.showInputDialog(null, "Please enter ending arc for job " + (i + 1) + ": "));
}
int[][] adj = adjMatrix(begin, end, numJobs);
level(adj, root, level);
}
public static int[][] adjMatrix(int[] begin, int[] end, int numJobs)
{
int[][] adj = new int[numJobs][numJobs];
for (int i = 0; i < numJobs; i++)
{
for (int j = 0; j < numJobs; j++)
{
adj[i][j] = 0;
}
}
for (int i = 0; i < numJobs; i++)
{
adj[begin[i]][end[i]] = 1;
System.out.println(Arrays.toString(adj));
}
return adj;
}
public static void level(int[][] adj, int root, int l)
{
int[] lev = new int[numJobs];
lev[0] = 0;
for (int i = 0; i < numJobs; i++)
{
if (adj[i][root] == 1)
{
lev[i] = l + 1;
level(adj, i, l + 1);
}
}
System.out.println(Arrays.toString(adj));
}
}
答案 0 :(得分:0)
好的我明白了:
package husalgo;
import java.util.Arrays;
import javax.swing.JOptionPane;
public class HusAlgo
{
private static final int numJobs = 5;
static int[] lev = new int[numJobs];
private static final int[][] adj = new int[numJobs][numJobs];
public static void main(String[] args)
{
int lev = 0;
int root = 0;
int numJobs = Integer.parseInt(JOptionPane.showInputDialog(null, "Please enter number of jobs: "));
int machines = Integer.parseInt(JOptionPane.showInputDialog(null, "Please enter number of machines: "));
int[] begin = new int[numJobs - 1];
int[] end = new int[numJobs - 1];
//Grab input for the begining and ending arcs
for (int i = 0; i < begin.length; i++)
{
begin[i] = Integer.parseInt(JOptionPane.showInputDialog(null, "Please enter the begining arc for job " + (i + 1) + ": "));
end[i] = Integer.parseInt(JOptionPane.showInputDialog(null, "Please enter ending arc for job " + (i + 1) + ": "));
}
//Setup adjacency matrix
for (int i = 0; i < numJobs; i++)
{
for (int j = 0; j < numJobs; j++)
{
adj[i][j] = 0;
}
}
for (int i = 0; i < numJobs - 1; i++)
{
adj[begin[i]][end[i]] = 1;
}
level(root, lev);
}
public static void level(int root, int l)
{
for (int i = 0; i < numJobs; i++)
{
if (adj[i][root] == 1)
{
lev[i] = l + 1;
level(i, l + 1);
}
}
System.out.println("Levels: " + Arrays.toString(lev));
}
}
这是我的工作代码。当我创建numJobs全局时,我也用于数组长度。我将变量移动到输入并从递归方法中拉出adj [] []参数。当递归发生时,它正在创建另一个数组实例并导致堆栈错误。谢谢!帮助...