w3resource

Java Exercises: Searches a value in an m x n matrix

Java Basic: Exercise-120 with Solution

Write a Java program that searches a value in an m x n matrix.

Sample Solution:

Java Code:

public class Main {
public static void main(String[] args) {
 // int target = 5;
  int target = 0;
  int[][] matrix = new int[3][3];
        for (int row = 0; row < 3; row ++)
            for (int col = 0; col < 3; col++)
                matrix[row][col] = (1 + row * 3 + col);

        for (int row = 0; row < 3; row ++)
        {
            for (int col = 0; col < 3; col++)
              {
                System.out.print(matrix[row][col]+" ");
                if (col == 2)
                System.out.println();
              }
        }
      System.out.print(Boolean.toString(searchMatrix(matrix, target))); 
    }
  public static boolean searchMatrix(int[][] matrix, int target) {
        if (matrix.length == 0 || matrix[0].length == 0) {
            return false;
        }
        int m = matrix.length;
        int n = matrix[0].length;
        int lower = 0;
        int higher = m * n - 1;
        while (lower <= higher) {
            int mid = (lower + higher) >> 1;
            int val = matrix[mid / n][mid % n];
            if (val == target) {
                return true;
            }
            if (val < target) {
                lower = mid + 1;
            } else {
                higher = mid - 1;
            }
        }
        return false;
    }
}


Sample Output:

1 2 3 
4 5 6 
7 8 9 
false

Pictorial Presentation:

Java exercises: Searches a value in an m x n matrix
Java exercises: Searches a value in an m x n matrix

Flowchart:

Flowchart: Java exercises: Searches a value in an m x n matrix

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Java program to get the first occurrence (Position starts from 0.) of an element of a given array
Next: Write a Java program to reverse a given linked list.

What is the difficulty level of this exercise?



Java: Tips of the Day

Try and catch:

Java is excellent at catching errors, but it can only recover gracefully if you tell it what to do. The cascading hierarchy of attempting to perform an action in Java starts with try, falls back to catch, and ends with finally. Should the try clause fail, then catch is invoked, and in the end, there's always finally to perform some sensible action regardless of the results. Here's an example:

try {
        cmd = parser.parse(opt, args); 
       
        if(cmd.hasOption("help")) {
                HelpFormatter helper = new HelpFormatter();
                helper.printHelp("Hello ", opt);
                System.exit(0);
                }
        else {
                if(cmd.hasOption("shell") || cmd.hasOption("s")) {
                String target = cmd.getOptionValue("tgt");
                } // else
        } // fi
} catch (ParseException err) {
        System.out.println(err);
        System.exit(1);
        } //catch
        finally {
                new Hello().helloWorld(opt);
        } //finally
} //try

It's a robust system that attempts to avoid irrecoverable errors or, at least, to provide you with the option to give useful feedback to the user. Use it often, and your users will thank you!

Ref: https://red.ht/3EZc9OC