I need to implement a method/function to determine if a number is present in a matrix. The given matrix is sorted in descending order both in rows and columns. Here there are three examples of the defined matrix:
private static int[][] matrix1= {
{69, 57, 43, 28, 14},
{68, 56, 35, 25, 13},
{66, 55, 34, 22, 8},
{64, 52, 32, 21, 7},
{62, 47, 31, 17, 5}
};
private static int[][] matrix2 = {
{62, 47, 31, 17, 5}
};
private static int[][] matrix3 = {
{14},
{13},
{9},
{7},
{5}
};
The function, should follow the Divide and Conquer principle. My idea is to look for an element of a matrix that acts as a pivot, and from it, divide the matrix. If the number we are looking for is larger than the pivot, we would keep the columns on the left of the pivot and its own but with the previous rows of the pivot. If the pivot is larger, it would be the other way around (the next columns and its own with the lower rows). In addition, to optimize the code, first I would need to search for the number in pivot´s column and then keep looking in the rest of the columns (but I don't know how to implement this in my code).
My code is the following but when running, this error keeps popping up java.lang.StackOverflowError.I understand that I am saturating the buffer's memory but I shouldn’t need to modify it to make the function work. I would like to avoid it unless it is the only solution.
public boolean contains(int[][] matrix, int num) {
int rowMin = 0;
int rowMax = matrix.length-1;
int colMin = 0;
int colMax = matrix[0].length-1;
return containsAux(matrix, rowMin, colMin, rowMax, colMax, num);
}
private boolean containsAux(int[][]matrix, int rowMin, int colMin, int rowMax, int colMax, int num) {
boolean resul=false;
int col= (colMax+colMin)/2;
int row=(rowMax+rowMin)/2;
int pivote= matrix[row][col];
if(pivote==num) {
resul=true;
}else if(pivote<num && rowMin>=0 && colMin>=0) {
containsAux(matrix,row-1,col,rowMin,col,num);
containsAux(matrix,row-1,col-1,rowMin,col-1,num);
fila-=1;
containsAux(matrix,row+1,col-1,rowMax,col-1,num);
}else if (pivote> num && rowMax<matrix.length && rowMax<matrix[0].length) {
containsAux(matrix,row+1,col,rowMax,col,num);
rowMin-=1;
containsAux(matrix,rowMin+1,col+1,row,col+1,num);
containsAux(matrix,row+1,col+1,rowMax,col+1,num);
}
return resul;
}
My test code is:
public class Prueba {
private static int[][] matrix = {
{69, 57, 43, 28, 14},
{68, 56, 35, 25, 13},
{66, 55, 34, 22, 8},
{64, 52, 32, 21, 7},
{62, 47, 31, 17, 5}
};
public static void main(String[] args) {
CartonBingo cb= new CartonBingo();
System.out.println(cb.contains(matrix, 35));
}
}
My question is: Is there another approach to do this following the Divide and Conquer principle, or should I change the code to run it smoothly? Thank you in advance.