Re: [問題] 降階法
class Matrix {
public:
long det() {
if(data.size() != data.at(0).size())
return 0;
vector<int> rows;
for(int i = 0 ; i < data.size() ; i++)
rows->push_back(i);
return det(rows,0);
}
private:
vector<vector<int>> data;
long det(vector<int> rows,int colIndex) {
long sum = 0;
int sig = 1;
for(int i = 0 ; i < rows.size() ; i++) {
vector<int> newRows(rows);
newRows.erase(newRows.begin()+i);
sum += sig * data[rows.at(i)][colIndex] * det(newRows,colIndex+1);
sig *= -1;
}
return sum;
}
};
※ 引述《tyc5116 (累人啊....)》之銘言:
: ※ 引述《tyc5116 (累人啊....)》之銘言:
: 不好意思,這個問題還是沒解決...@@
: 附上我目前的進度
: http://tinyurl.com/yjrabx4
: 用vector寫的,降階的部份大致都弄好了
: 只是在做運算的部份迴圈不知道怎麼設計
: 主要用遞迴的方式寫(實際上我也只想到這個方法...@@)
: 可是因為平常很少用遞迴寫程式,所以卡了這麼久
: 主要的程式在這部份
: vector<vector<int> > Matrix::Reduce(vector<vector<int> > submatrix,
: int column,int& value){
: vector<vector<int> > smallmatrix(submatrix.size()-1,vector<int>(
: submatrix.size()-1));
: vector<vector<int> > tmpmatrix;
: vector<int> tmprow;
: static int sum=0;
: int r=1,c=0;
: int s=1;
: int col=0;
: int cons=0;
: int ans=0;
: int rr=0;
: //降階
: for (int i=0;i<smallmatrix.size();++i){
: for (int j=0;j<smallmatrix[0].size();++j){
: if (j==column){++c;}
: smallmatrix[i][j]=submatrix[r][c++];
: }
: c=0;
: ++r;
: }
: cout<<"降階後的陣列"<<endl;
: for (int j=0;j<smallmatrix.size();++j){
: for (int k=0;k<smallmatrix[0].size();++k){
: cout<<smallmatrix[j][k]<<" ";
: }
: cout<<endl;
: }
: if (smallmatrix.size()>1){
: tmpmatrix=smallmatrix;
: tmprow.resize(smallmatrix.size());
: tmprow[0]=smallmatrix[0][0];
: tmprow[1]=smallmatrix[0][1];
: for (int i=0;i<smallmatrix.size();++i){
: tmpmatrix=Reduce(smallmatrix,i,value);//若階數>1便再降階
: cons=tmprow[rr++];
: sum+=cons*s*tmpmatrix[0][0];
: s*=-1;
: }
: }
: return smallmatrix;
: 個人認為應該把這裡解決掉就好.....可是我想好久了....@@
: 再麻煩大大們解答一下,謝謝
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 211.74.9.2
推
10/17 17:12, , 1F
10/17 17:12, 1F
討論串 (同標題文章)