我試圖找到子數組左上角的索引,其總和最大。我見過找到最大子數組的算法,但這些算法不適合我的需求,因為我需要在使用算法之前設置子數組的維度。/** * Finds the rectangle of height h and width w within the band * row0 <= row < row0 + h with the most "ink" in it, or the largest sum in it * @param int[][] image - A 2d array of light intensity values of each pixel in an image * @param h, w - Dimensions of the specified rectangle with height h and width w * @param row0 - the index of where it should start constructing rectangles? (I'm not sure) * @return The index of the leftmost column of the rectangle */private int findHorzPosition(int[][] image, int row0, int h, int w) {int maxSum = 0;int maxRow = 0; for(int p = row0; p <= image.length - 1; p++) { int[][] tempArr = new int[image.length - row0][image[p].length - 1]; for(int q = 0; q <= image[p].length - 1; q++) { tempArr[p][q] = image[p][q]; for(int i = 0; i <= tempArr.length - 1; i++) { int rowSum = 0; for(int j = 0; j <= tempArr[i].length - 1; j++) { rowSum += image[i][j]; } if (rowSum > maxSum) { maxSum = rowSum; maxRow = i; } } } } return maxRow;}這是我擁有的,但我似乎無法讓它工作。對我能做些什么有什么建議嗎?
1 回答

藍山帝景
TA貢獻1843條經驗 獲得超7個贊
該方法的javadoc說:findHorzPosition
查找帶子中具有最多“墨水”或最大總和的帶子內的高度和寬度的矩形
h
w
row0 <= row < row0 + h
這意味著波段很高,即該方法應搜索具有行中頂行的矩形。
因此,代碼不應具有 p
1 循環。h
row0
javadoc還說:
@return
矩形最左側列的索引
代碼返回 。對于總和最大的矩形,代碼應返回 q
1 的值,而不是為總和最大的行返回 的值。maxRow
i
1)變量名稱毫無意義,使得代碼難以理解。具有單字符名稱的局部變量應僅在含義明顯時使用,例如 i
, j
, ...表示索引,或 x
、y
、z
表示坐標。在你的代碼中,p
、q
、i
和 j
不是明顯的名稱。將 q
重命名為左側
,將 i
重命名為行
,將 j
重命名為 col
。
添加回答
舉報
0/150
提交
取消