【发布时间】:2014-09-03 16:07:41
【问题描述】:
我试图找到找到方阵行列式的代码,我遇到了这个代码。
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);
}
但我无法理解第 20-29 行,即从另一行的倍数中减去行的位置。我的意思是为什么这里需要while循环?如我一般
减去商*股息,它应该总是 0 ,对吧?所以我认为它应该只是一次迭代。那么,为什么我们需要执行这个mat[row].swap(mat[col]); 操作呢?
提前致谢。
【问题讨论】:
标签: c++ matrix gaussian determinants