Matrix Search [codingblocks]

Given an n x m matrix, where every row and column is sorted in increasing order, and a number x . Find if element x is present in the matrix or not.


Input Format
First line consists of two space separated integers N and M, denoting the number of element in a row and column respectively. Second line of each test case consists of N*M space separated integers denoting the elements in the matrix in row major order. Third line of each test case contains a single integer x, the element to be searched.

Constraints
1 <= N,M <= 30 0 <= A[i] <= 100

Output Format
Print 1 if the element is present in the matrix, else 0.

Sample Input
3 3
3 30 38
44 52 54
57 60 69
62

Sample Output
0

Explanation
Search the element in the sorted matrix. If the element is present print 1 otherwise print 0. In the sample input,in first case 62 is not present in the matrix so 0 is printed. Similarly, for second case 55 is present in the matrix so 1 is printed.



Java Code:




/*
Amit Kumar
07-12-2020
2 way binary search will not work, see: https://ide.geeksforgeeks.org/d4L87YqYtW
IDE Code: https://ide.geeksforgeeks.org/87JKxb9IKA
*/

package array;
import java.util.Scanner;

public class Array_MatrixSearch {
    public static Scanner scanner = new Scanner(System.in);
    public static void main(String[] args) {
        int row = scanner.nextInt();
        int col = scanner.nextInt();
        int[][] matrix2d = new int[row][col];

        for (int i=0; i<row; i++) {
            for (int j=0; j<col; j++) {
                matrix2d[i][j] = scanner.nextInt();
            }
        }

        int searchElement = scanner.nextInt();
        System.out.println(search2DMetrix(matrix2d, searchElement));
    }

    private static int search2DMetrix(int[][] matrix2d, int searchElement) {
        int row, column;
        row = 0;
        column = matrix2d[0].length - 1;

        while (row < matrix2d.length && column >= 0) {
            if (matrix2d[row][column] == searchElement) {
                return 1;
            } else if (matrix2d[row][column] > searchElement) {
                column--;
            } else {
                row++;
            }
        }
        return 0;
    }
}

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )