samedi 28 janvier 2017

Find the number of negative numbers in a column-wise & row-wise sorted matrix (using for-loop C++)

I am trying to do a problem stated as follows: **Find the number of negative numbers in a column-wise & row-wise sorted matrix M[][]. **

Example:
Input:  M =  [-3, -2, -1,  1]
             [-2,  2,  3,  4]
             [4,   5,  7,  8]
Output : 4
We have 4 negative numbers in this matrix

This problem is taken from Geeksforgeeks

I was trying an approach with for-loop instead of the one explained with while-loop in the post. Following is my code function. Can someone point me where the mistake is? and if possible, what are some general considerations to be taken in case of a for-loop and while-loop?

int findNegativeinaSortedMatrix(vector<vector<int>> M,int rowSize,int colSize){

int count = 0;

for (int r=0; r<rowSize; r++){
    for (int c=colSize-1; c>=0; c--){
        cout << M[r][c] << endl;
        if (M[r][c] < 0) {
            count = c+1;
            r= r + 1;
        }
    }
}
return count;

}

Aucun commentaire:

Enregistrer un commentaire