Skip to content

Instantly share code, notes, and snippets.

@rigibun
Last active December 19, 2015 07:09
Show Gist options
  • Save rigibun/5916274 to your computer and use it in GitHub Desktop.
Save rigibun/5916274 to your computer and use it in GitHub Desktop.
#include <iostream>
int determinant(int** matrix,int n)
{
int ans = 0;
if(n == 2)
{
ans = matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0];
return ans;
}
for(int i = 0; i < n; i++)
{
int** array = new int*[n-1];
for(int j = 0; j < n-1; j++)
{
array[j] = new int[n-1];
}
int x = 0, y = 0;
for(int j = 1; j < n; j++)
{
x = 0;
for(int k = 0; k < n; k++)
{
if(k == i) continue;
array[y][x++] = matrix[j][k];
}
y++;
}
int sum = matrix[0][i] * determinant(array, n-1);
if(i % 2) sum *= -1;
ans += sum;
for(int j = 0; j < n-1; j++)
delete[] array[j];
delete[] array;
}
return ans;
}
int main(void)
{
using namespace std;
int n;
cin >> n;
int** matrix = new int*[n];
for(int i = 0; i < n; i++)
{
matrix[i] = new int[n];
}
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
cin >> matrix[i][j];
cout << determinant(matrix, n) << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment