【发布时间】:2016-11-26 17:58:23
【问题描述】:
我正在尝试解决一个动态规划问题,包括拥有一个矩阵,找到最大大小的排序子矩阵。
我想使用动态编程来找到解决方案,但我没有得到正确的结果。
我的程序包含两种方法:第一种方法递归地检查参数给定位置附近的元素。然后,在第二种方法中,我调用前一种方法来查找子矩阵的最大阶数,但它没有返回正确的结果。
例如,对于这个矩阵并使用 new Solution(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;
}
}
【问题讨论】:
-
一个排序的子矩阵的所有值从左到右和从上到下(严格来说?)增加以符合可能的解决方案?
-
不应该返回
6吗? 1、2、6、7、9、10 在左上角。 -
对不起,它应该返回3,这是最大排序子矩阵的顺序:在第二行1、2、10;在第三行 6、7、20 和第四行 9、10、23 中。排序后的子矩阵需要使其所有元素按行和列以升序排列。
-
那么排序后的子矩阵需要是方阵?
标签: java algorithm dynamic-programming