Input Parameters: The function search takes a 2D matrix (matrix) and an integer (x) as input.
Initialization: The variables len, i, and j are initialized. len represents the length of one side of the square matrix (assuming it's a square matrix). i is initialized to the last index of the matrix (bottom-left corner), and j is initialized to 0 (bottom-left corner).
Search Loop: The code uses a while loop to iterate through the matrix until either i goes below 0 or j exceeds the matrix size.
Inside the loop, it checks if the current element at position (i, j) is equal to the target value x. If true, it creates a Pair object with the indices (i, j) and returns it. If the current element is greater than x, it means the target value may be in the upper row, so it decrements i.
If the current element is less than or equal to x, it means the target value may be in the right column, so it increments j.
Result: If the loop exits without finding the target value, it returns a Pair with indices (-1, -1), indicating that the value was not found in the matrix.
Output: The function returns a Pair representing the indices of the found element or (-1, -1) if the element is not present.
import java.util.*;
import java.io.*;
/*************************************
*
* Following is the Pair Class structure.
*
* class Pair{
* int x; int y;
*
* Pair(int x, int y){
* this.x = x;
* this.y = y;
* }
* }
*
*************************************/
public class Solution {
public static Pair search(int[][] matrix, int x) {
int len = matrix.length - 1;
int i = len;
int j = 0;
while (i > -1 && j <= len) {
if (matrix[i][j] == x) {
return new Pair(i, j);
}
if (matrix[i][j] > x) {
--i;
} else {
j++;
}
}
return new Pair(-1, -1);
}
}