我做了一个小程序,用一些递归来计算矩阵的行列式。我尝试了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 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));
}
答案 0 :(得分:2)
这会导致问题(下一行是相关的):
int[][] newMatrix = new int[matrix.length][matrix[0].length];
您实际上创建了与原始大小完全相同的子矩阵,然后应用递归。
我假设您要创建完全排除row
和col
的子矩阵,因此每个维度的尺寸小一个,并将内容移到左侧和顶部指定row
和col
。