If li=0 ,and we use arr[li-1][bi] ,here it takes garbage value,please explain me how to find the sum of all sub matrix by the method taught in the video.
I did'nt understand how to find the sum of all submatrix
You have to impose extra if else conditions and handle that separately. Refer this discussion Sum of all submatrix from a given matrix
I write the code for the program but it shows right answer for 2x2 matrix and it shows wrong answer for 3x3 matrix
#include<bits/stdc++.h>
using namespace std;
int main(){
int n,sum;
cin>>n;
int a[n][n];
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
cin>>a[i][j];
}
}
for(int i=0;i<n;i++){
sum=0;
for(int j=0;j<n;j++){
sum+=a[i][j];
a[i][j]=sum;
}
}
for(int i=0;i<n;i++){
sum=0;
for(int j=0;j<n;j++){
sum+=a[j][i];
a[i][j]=sum;
}
}
sum=0;
for(int li=0;li<n;li++){
for(int lj=0;lj<n;lj++){
for(int bi=li;bi<n;bi++){
for(int bj=lj;bj<n;bj++){
if(li==0 && lj==0){
sum+=a[bi][bj];
}
else if(li==0 && lj!=0){
sum+=a[bi][bj]-a[bi][lj-1];
}
else if(lj==0 && li!=0){
sum+=a[bi][bj]-a[li-1][bj];
}
else{
sum+=a[bi][bj]-a[bi][lj-1]-a[li-1][bj]+a[li-1][lj-1];
}
}
}
}
}
cout<<sum<<’\n’;
return 0;
}
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.