Вычислить определитель матрицы рекурсивно - C#
Формулировка задачи:
Найти разложением по первой строке
Код компилируется, но не корректно выполняется.
Буду рад любым дельным замечаниям и советам.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Task14._17
{
class Program
{
static int Det(int[,] A, int g)
{
int i, j, k, u;
int result = 0;
///Make B
int n = A.GetLength(0);
int[,] B = new int[n - 1, n - 1];
int b = B.GetLength(0)-1;
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
if ((i != 0) && (j > 0))
{
B[i - 1, j - 1] = A[i, j];
}
}
}
///Вычисление определителя
if (n > 0)
{
if (n == 1)
{
result = A[0, 0];
}
if (n == 2)
{
result = A[0, 0] * A[1, 1] - A[1, 0] * A[0, 1];
}
else
{
for (i = 0; i < A.GetLength(0) - 1; i++)
{
for (j = 0; i < A.GetLength(1) - 1; j++)
{
u = (i + j) % 2;
if (u == 0)
{
k = 1;
}
else
{
k = -1;
}
i = 0;
j=0;
result = (A[i, j] * ((B[i, 0] * B[i + 1, j + 1]) - (B[b, 0] * B[b-1, 1])));
}
}
for (i = 0; i < A.GetLength(0) - 1; i++)
{
for (j = 0; j < A.GetLength(0) - 1; j++)
{
if ((i != 0) && (j > 0))
{
A[i - 1, j - 1] = A[i, j];
}
}
}
if (g == A.GetLength(0))
return result;
else
{///уменьшать размер А
result = result * Det(A, g++);
}
}
}
return result;
}
static void Main(string[] args)
{
int g = 0;
int n = int.Parse(Console.ReadLine());
int[,] A = new int[n, n];
int[,] B = new int[n - 1, n - 1];
Matrix(n, out A);
Console.WriteLine();
Console.WriteLine(Det(A, g));
Console.ReadKey();
}
static void Matrix(int n, out int[,] C)
{
// Задание матрицы
int[,] Array = new int[n, n];
{
Random rnd = new Random();
int a = 0;
// Заполнение матрицы случайными числами
for (int i = 0; i < n && a < n; i++)
{
Array[a, i] = rnd.Next(5);
if (i == n - 1 && a < n - 1)
{
a += 1;
i = -1;
}
}
a = 0;
for (int i = 0; i < n && a < n; i++)
{
// Вывод матрицы
Console.Write("{0} ", Array[a, i]);
if (i == n - 1 && a < n - 1)
{
a += 1;
i = -1;
Console.WriteLine();
}
}
C = Array;
}
}
}
}Решение задачи: «Вычислить определитель матрицы рекурсивно»
textual
Листинг программы
using System;
namespace ConsoleApplication41
{
class Program
{
static void Main()
{
double[,] matrix =
{
{1, 2, 3},
{4, 10, 6},
{7, 8, 9}
};
var det = DetRec(matrix);
Console.WriteLine(det);
}
private static double DetRec(double[,] matrix)
{
if (matrix.Length == 4)
{
return matrix[0, 0]*matrix[1, 1] - matrix[0, 1]*matrix[1, 0];
}
double sign = 1, result = 0;
for (int i = 0; i < matrix.GetLength(1); i++)
{
double[,] minor = GetMinor(matrix, i);
result += sign*matrix[0, i]*DetRec(minor);
sign = -sign;
}
return result;
}
private static double[,] GetMinor(double[,] matrix, int n)
{
double[,] result = new double[matrix.GetLength(0) - 1, matrix.GetLength(0) - 1];
for (int i = 1; i < matrix.GetLength(0); i++)
{
for (int j = 0, col = 0; j < matrix.GetLength(1); j++)
{
if (j == n)
continue;
result[i - 1, col] = matrix[i, j];
col++;
}
}
return result;
}
}
}