I have a kattis task that I'm struggling with to complete. The task is to "find a set of at least k connected entries in a matrix, such that the difference between the largest and smallest entry in the set was minimized".
The input is first the size of the matrix:
5 10
Then the values of the matrix:
0 0 3 46 0 46 0 0 12 12 0 0 13 50 49 46 11 10 10 11 0 51 51 49 99 99 89 0 0 10 0 0 48 82 70 99 0 52 13 14 51 50 50 51 70 35 70 10 14 11
After that there's the ammount of k values:
6
And then the actual values on k:
1 5 10 12 47 50
The task states that: "An entry in the matrix, a(i,j), is adjacent to the entries a(i,j+1), a(i+1,j), a(i,j-1) and a(i-1,j). A set of entries are connected if for every pair of entries in the set, there is a connecting path of adjacent entries in it.".
For the values given the output should be:
0 0 3 4 89 99
I have written the code to take all the inputs:
Scanner sc = new Scanner(System.in);
int r = sc.nextInt();
int c = sc.nextInt();
// fill with values
int[][] dimMat = new int[r][c];
for (int i = 0; i < dimMat.length; i++) {
for (int j = 0; j < dimMat[i].length; j++) {
dimMat[i][j] = sc.nextInt();
}
}
int n = sc.nextInt();
int[] myK = new int[n];
// fill k
for(int k= 0; k< myK.length; k++){
myK[k] = sc.nextInt();
}
But have no idea how to traverse the matrix, get all the different paths or find the value they ask for. I've been googling dynamic programming and other stuff for days without any result.
Thanks in advance for any help.