In this post, you will learn how to search for a specific element in a Matrix using Java. To search, you can use nested loops to traverse through the matrix and check each element until you find the target value. Once you find the element, you can obtain its row and column indices.
Here’s a Java program that demonstrates how to search for a specific element in a matrix and determine its position:
package com.javacodepoint.array.multidimensional;
public class MatrixSearch {
// search element in matrix
public static int[] searchElement(int[][] matrix, int target) {
int rows = matrix.length;
int cols = matrix[0].length;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (matrix[i][j] == target) {
return new int[] { i, j };
}
}
}
// If the element is not found, return {-1, -1}
return new int[] { -1, -1 };
}
// main method to test
public static void main(String[] args) {
int[][] matrix = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
int target = 5;
int[] position = searchElement(matrix, target);
if (position[0] != -1 && position[1] != -1) {
System.out.printf("Element %d found at position [%d, %d]\n", target, position[0], position[1]);
} else {
System.out.println("Element not found in the matrix.");
}
}
}
OUTPUT:
Element 5 found at position [1, 1]
Explanation:
In this program, we have a method searchElement
that takes a 2D integer array matrix
and an integer target
as inputs. The method iterates through the matrix using nested loops and checks each element. If the target element is found, it returns an array containing its row and column indices. If the element is not found, it returns an array with the values {-1, -1}.
See also: Find the Smallest Element in a Matrix.
Looks Important