HiveBrain v1.2.0
Get Started
← Back to all entries
patterncMinor

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

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
containingandalgorithmfindingdimensionalfrommatrixcomplexitydevise

Problem

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 at least the number of 1's row (i+1). Find a method and write a C program to count the number of 1's in a 2D matrix. The complexity of the algorithm should be order n.

The question is from Cormen's Algorithm Book. Kindly point out the mistakes in my algorithm and hopefully suggest a better way.

#include
 #include

  int **map; 
   int getMatrix();

  main()
  {
   int n,i,j,t;
 j=0;
 n=getMatrix();
   i=n-1;  
    int sum[n];
   for(t=0;t=0) && (j0))  
               sum[t]=sum[t+1];
             }
       int s=0;
          for (t=0;t='0' && c='0' && c<='9'));                  
    map[i][j]=c-'0';
} 
}
     fclose(input);
  return nVer;
  }

Solution

I think your main loop should be something more along the lines of

row = n-1;      // start at bottom row 
for (col=0; col= 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);

Code Snippets

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

Context

StackExchange Code Review Q#15044, answer score: 2

Revisions (0)

No revisions yet.