简体   繁体   中英

devise an O(N) algorithm finding No of 1's from a 2D matrix[N][N] containing 1's and 0's

Assume a 2D [n][n] matrix containint only 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 at least the no, of 1's row (i+1) . Find a method and write ac program to count the no of 1's in a 2D matrix. The complexity of the algorithm should be O(n).

The question is from Cormen's Algorithm Book, and below is my implementation for this problem. Kindly point out the mistakes in my algorithm and/or perhaps suggest a better way. Thanks!

#include <stdio.h>
#include <stdlib.h>

int **map;
int getMatrix();

main()
{
    int n,i,j,t;
    j=0;
    n=getMatrix();
    i=n-1;  
    int sum[n];
    for(t=0;t<n;t++)
        sum[t]=0;
    int count=0; 
    while ( (i>=0) && (j<n) )
    {
        if ( map[i][j] == 1 )
        {
            j++;
            count=count+1;
        }
        else
        {
            if (i==(n-1))
            {
                sum[i]=count;
                count=0;
                            i--;
            }   
            else            
            {
                sum[i]=sum[i+1]+count;
                count=0;            
                i--;
            }
        }
    }
    for (t=0;t<n;t++)
    { 
        if ((t==(n-1)) && (sum[t]==0))
            sum[t]=0;
        else if ((sum[t]==0) && (sum[t+1]>0))  
            sum[t]=sum[t+1];
    }
    int s=0;
    for (t=0;t<n;t++)
        s=s+sum[t];
    printf("\nThe No of 1's in the given matrix is %d \n" ,s);
}

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;
} 

it is easier to find problem when you first describe what you want to do. Anyway, seems to me that you have a problem on the if, you set

i == (n-1), on the initialization phase, and each time you enter this if the statmnet is correct and you don;t reduce i,

if (i==(n-1))
                {
                sum[i]=count;
                count=0;

                **i--;**
            }   
            else            
            {
                sum[i]=sum[i+1]+count;
                count=0;            
                i--;
            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM