Assume a 2d [n][n] Matrix of 1's and 0's/ All the 1's in any row should come before 0's/The number of 1's in any row i should be atleast the no of 1's row (i+1). find a method and write a c program to count the no of 1's in a 2 d matrix.The complexity of the algorithm should be order n.
The Question is from Cormen's Algorithm Book and here below is my implementation for this problem.Kindly point out the mistakes in my algorithm and Hopefully suggest me a better way .Thanks!
#include<stdio.h>
#include<stdlib.h>
int **map;
int getMatrix();
main()
{
int row,col,sum,n;
n=getMatrix();
sum=0;
row = n-1; // start at bottom row
for (col=0; col<n; col++) { // read columns from left to right
while ((row >= 0) && (map[row,col] == 0)) { // while not out of rows, and on a 0
sum += col; //add count of 1s to total
row--; //move to next row up
}
// do nothing if we're on a 1, just move to next column.
}
if (row >= 0)
sum += (row+1)*col; // add in any leftover rows of all 1s
printf("sum is %d\n",sum);
}
int getMatrix()
{
FILE *input=fopen("matrix.txt","r");
char c;
int nVer=0,i,j;
while((c=getc(input))!='\n')
if(c>='0' && c<='9')
nVer++;
map=malloc(nVer*sizeof(int*));
rewind(input);
for(i=0;i<nVer;i++)
{
map[i]=malloc(nVer*sizeof(int));
for(j=0;j<nVer;j++)
{
do
{
c=getc(input);
}while(!(c>='0' && c<='9'));
map[i][j]=c-'0';
}
}
fclose(input);
return nVer;
}