Monday, November 7, 2022

Search in a matrix

 

Problem:

Given a matrix mat[][] of size N x M, where every row and column is sorted in increasing order, and a number X is given. The task is to find whether element X is present in the matrix or not.


Example 1:

Input:
N = 3, M = 3
mat[][] = 3 30 38 
         44 52 54 
         57 60 69
X = 62
Output:
0
Explanation:
62 is not present in the
matrix, so output is 0

My Answer:

    public static int matSearch(int mat[][], int N, int M, int X)
    {
        for ( int n = 0 ; n < N ; n++ ) {
            for ( int m = 0 ; m < M ; m++ ) {
                if ( mat[n][m] == X ) {
                    return 1;
                }
            }
        }
        
        return 0;
    }

No comments:

Post a Comment

Search in a matrix

  Problem: Given a matrix  mat [][] of size  N  x  M , where every row and column is sorted in increasing order, and a number  X  is given. ...