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:
Flowchart:
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?
Test your Programming skills with w3resource's quiz.
Java: Tips of the Day
How to sort an ArrayList?
Collections.sort(testList); Collections.reverse(testList);
That will do what you want. Remember to import Collections though!
Ref: https://bit.ly/32urdSe
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework