I was trying to find the code for finding the determinant of a square matrix , and I came across this code.
int det(vector<vector<int> > mat) {
int n = mat.size();
for(int col = 0; col < n; ++col) {
bool found = false;
for(int row = col; row < n; ++row) {
if(mat[row][col]) {
mat[row].swap(mat[col]);
found = true;
break;
}
}
if(!found) {
return 0;
}
for(int row = col + 1; row < n; ++row) {
while(true) {
int del = mat[row][col] / mat[col][col];
for (int j = col; j < n; ++j) {
mat[row][j] -= del * mat[col][j];
}
if (mat[row][col] == 0)
break;
else
mat[row].swap(mat[col]);
}
}
}
li res = 1;
for(int i = 0; i < n; ++i) {
res *= mat[i][i];
}
return abs(res);
}
But I am having trouble understanding line 20-29 i.e where the subtraction of row from multiple of another row is performed. I mean why the while loop is required here ? as I am
subtracting the quotient*dividend , It should always be 0 , right ? So I think it should be just one iteration. So , why we need to perform this mat[row].swap(mat[col]);
operation ?
Thanks in advance.