我想解决一个动态编程问题,它包含一个矩阵,找到最大尺寸的排序子矩阵。使用动态编程查找最大尺寸的排序子矩阵
我想使用dinamic编程来找到解决方案,但我没有得到正确的结果。我的程序由两种方法组成:第一种方法递归地检查元素附近的位置到参数给定的位置。然后,在第二种方法中,我调用前一个来查找子矩阵的最大顺序,但它不返回正确的结果。
例如,对于这个矩阵,并呼吁用新的解决方案类(5,6)
10, 1, 4, 1, 4, 0
1, 2, 10, 6, 2, 1
6, 7, 20, 10, 1, 2
9, 10, 23, 0, 3, 5
10, 11, 24, 1, 0, 2
它应该返回4. 这里是我的代码:
import java.util.Scanner;
public class Solution {
private int[][] mat;
Scanner sc = new Scanner(System.in);
int n, m;
public Solution(int n, int m) {
this.n = n;
this.m = m;
mat = new int[n][m];
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++)
mat[i][j] = sc.nextInt();
for(int i = 0; i < n; i++) {
System.out.println();
for(int j = 0; j < m; j++)
System.out.print(mat[i][j] + "\t");
}
}
public void call() {
int sol = maxSortedMatrix(mat);
System.out.println("Matrix of order " + sol);
}
private int nearElements(int i, int j, int[][] mat, int[][] maxLongi) {
// basically recursively check surrounding elements. If they are exist and smaller than
// current element, we should consider it as the longest increasing sub sequence. However if we
// already check one element, the value corresponding to that index pair should no longer be zero,
// thus no need to recursively calculate that value again.
if (maxLongi[i][j] == 0) {
// have not been visited before, need recursive calculation
// have not recursively checking.
int length = 1;
// up
if (i - 1 > -1 && mat[i][j] > mat[i - 1][j]) {
length = Math.max(length, 1 + nearElements(i - 1, j, mat, maxLongi));
}
// down
if (i + 1 < mat.length && mat[i][j] > mat[i + 1][j]) {
length = Math.max(length, 1 + nearElements(i + 1, j, mat, maxLongi));
}
// left
if (j - 1 > -1 && mat[i][j] > mat[i][j - 1]) {
length = Math.max(length, 1 + nearElements(i, j - 1, mat, maxLongi));
}
// right
if (j + 1 < mat[0].length && mat[i][j] > mat[i][j + 1]) {
length = Math.max(length, 1 + nearElements(i, j + 1, mat, maxLongi));
}
maxLongi[i][j] = length; // setting maxLenTailing value here to avoid additional recurssively checking
return length;
}
return maxLongi[i][j];
}
private int maxSortedMatrix(int[][] mat) {
if (mat == null || mat.length == 0 || mat[0] == null || mat[0].length == 0) {
return 0;
}
int[][] maxLength = new int[n][m];
// store the max length of increasing subsequence that ending at i and j.
int max = 0;
// top left to bottom right
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
// scan every element in the matrix.
maxLength[i][j] = nearElements(i, j, mat, maxLength);
max = Math.max(max, maxLength[i][j]);
}
}
return max;
}
}
一个有序子矩阵拥有这一切的从左至右,从上到下值(严格?)越来越有资格成为可能的解决方案? – maraca
它不应该返回'6'吗? 1,2,6,7,9,10在左上方。 – maraca
对不起,它应该返回3,这是最大的排序子矩阵的顺序:在第二行1,2,10;在第三行6,7,20和第四行9,10,23中。排序后的子矩阵需要以行和列的方式排列所有元素。 – DDN