Friday, July 3, 2015

C program to find the largest-sum (2*2)submatrix from a given n*n matrix




C program :

Copy the program to a notepad and save it as a .c file and open using turbo c++.




#include<stdio.h>
#include<conio.h>
void main()
{
int index[100][5]={0},a[5][5]={0},sum[100]={0},r,c,k=0,iv,jv,i,j,largest;
clrscr();
printf("Enter row and column value:");
scanf("%d%d",&r,&c);
printf("\nEnter the matrix\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&a[i][j]);
}
}
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
if((i<=r-2)&&(j<=c-2))
{
index[k][0]=i;
index[k][1]=j;
sum[k]=a[i][j]+a[i+1][j]+a[i][j+1]+a[i+1][j+1];
//printf("(%d %d) %d",i,j,sum[k]);
k++;
}
}
}
largest=sum[0];
iv=index[0][0];
jv=index[0][1];
for(i=1;i<=k;i++)
{
if(largest<sum[i])
{
largest=sum[i];
iv=index[i][0];
jv=index[i][1];
}
}
printf("the largest sum (2*2)subset matrix is:\n %d %d\n %d %d",a[iv][jv],a[iv][jv+1],a[iv+1][jv],a[iv+1][jv+1]);

getch();
}

No comments:

Post a Comment