Java 我的程序给了我一个堆栈溢出错误
我制作了一个小程序,用递归法计算矩阵的行列式。我尝试了一个5x5矩阵,得到了一个堆栈溢出错误。我知道递归可能太深了,但我不知道如何纠正它。有什么解决办法吗 这是我的密码:Java 我的程序给了我一个堆栈溢出错误,java,recursion,matrix,determinants,Java,Recursion,Matrix,Determinants,我制作了一个小程序,用递归法计算矩阵的行列式。我尝试了一个5x5矩阵,得到了一个堆栈溢出错误。我知道递归可能太深了,但我不知道如何纠正它。有什么解决办法吗 这是我的密码: /** * @requires matrix is at least 2x2 and has all real entries * @param matrix[][] a matrix * @param row is the row to be omitted * @param col is the column to
/**
* @requires matrix is at least 2x2 and has all real entries
* @param matrix[][] a matrix
* @param row is the row to be omitted
* @param col is the column to be omitted
* @requires @code col and @code row are
* @returns the @code matrix without column
*/
private static int[][] subMatrix(int[][] matrix, int row, int col){
int[][] newMatrix = new int[matrix.length][matrix[0].length];
int newRow = 0;
for ( int i = 0; i < matrix.length; i++){
int newCol = 0;
if ( i != row ){
for( int j = 0; j < matrix[i].length; j++){
if ( j != 0){
newMatrix[i][j] = matrix[newRow][newCol];
newCol++;
}
}
newRow++;
}
}
return newMatrix;
}
/**
* @requires matrix is at least 2x2 and has all real entries
* @param matrix[][] a matrix
* @returns the determinant of @code matrix
*/
private static int det(int[][] matrix){
int det = 0;
int rows = matrix.length;
int cols = matrix[0].length;
//handling base case
if(rows == 2 & cols == 2){
det = matrix[0][0]*matrix[1][1] - matrix[0][1]*matrix[1][0];
} else {
//expanding a row
if(rows > cols)
{
for(int i = 0; i < rows; i++){
det += matrix[0][i]*det(subMatrix(matrix, i, 0));
}
}
//expanding a column
else {
for(int i = 0; i < rows; i++){
det += matrix[i][0]*det(subMatrix(matrix, 0, i));
}
}
}
return det;
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the number of rows: ");
int rows = in.nextInt();
System.out.print("Enter the number of columns: ");
int cols = in.nextInt();
//reading in matrix
int[][] matrix = new int[rows][cols];
for(int i = 0; i < rows; i++){
System.out.print("Enter the entries of row " + i + ": ");
for (int j = 0; j < cols; j++){
matrix[i][j] = in.nextInt();
}
}
System.out.println("The determinant of the matrix is: " + det(matrix));
}
/**
*@requires matrix至少为2x2,并且具有所有实际条目
*@param matrix[]a矩阵
*@param row是要忽略的行
*@param col是要省略的列
*@requires@code col和@code row是
*@返回不带列的@code矩阵
*/
私有静态int[][]子矩阵(int[][]矩阵,int行,int列){
int[]newMatrix=newint[matrix.length][matrix[0.length];
int newRow=0;
对于(int i=0;i列)
{
对于(int i=0;i
这会导致问题(与下一行相关):
实际上,创建与原始子矩阵大小完全相同的子矩阵,然后应用递归
我假设您要创建完全排除
行
和列
的子矩阵,因此每个维度的大小都要小一个,并将内容向左和向上移动到指定的行
和列
是否适用于较小的矩阵?您当然知道,任何递归解决方案都可以作为非递归解决方案重新编写,通常使用某种堆栈。我建议你查一下这个,试试看。是的,它适合小的。我将尝试用堆栈编写它,看看它是如何运行的。我建议从一个文件中读取矩阵值(从那里通过管道),这样更容易测试。然后,如果您从eclipse或其他IDE运行它,请尝试从调试中调用它。在源代码中添加断点以查找错误。如果您已经共享了完整的代码、输入值和期望值,那么会更容易提供帮助。谢谢,这就解决了问题。我只是使新矩阵的维数比前一个矩阵的维数小一个。
int[][] newMatrix = new int[matrix.length][matrix[0].length];