我正在尝试编写一个获得两个参数int[] [] mat
和int num
的方法。
该方法在2D数组中搜索斜率或具有num之差的值序列,
这意味着该方法将搜索一个值,该值后跟一个比上一个值小“ num”的值。
最终,这些方法返回矩阵中存在的最长有效斜率的整数。
我将其分为三种方法:
公共类LongestSlope {
private static int _longestSlope = 0;
public static int LongestSlope(int[][] mat, int num)
{
checkEach (mat,0,0, num);
return _longestSlope;//_longestSlope;
}
private static boolean valid (int[][] mat, int row, int column)
{
boolean withinRowBounds = (row >= 0) && (row < mat.length);
boolean withinColumnBounds = (column >= 0) && (column < mat[0].length);
return withinRowBounds && withinColumnBounds;
}
private static int slopeLength (int[][] mat, int row, int column, int num)
{
int right = 1, left = 1, up = 1, down = 1;
if (valid(mat, row, column))
{
if (valid(mat, (row +1), column))
{
if (mat[row][column] - num == mat[row+1][column])
up += slopeLength(mat, (row +1), column, num);
}
if (valid(mat, (row -1), column))
{
if (mat[row][column] - num == mat[row-1][column])
down += slopeLength(mat, (row -1), column, num);
}
if (valid(mat, row, (column +1)))
{
if (mat[row][column] - num == mat[row][column+1])
right += slopeLength(mat, row, (column +1), num);
}
if (valid(mat, row, (column -1)))
{
if (mat[row][column] - num == mat[row][column-1])
left += slopeLength(mat, row, (column -1), num);
}
}
return max(max(right, left) , max(up, down));
}
private static void checkEach (int[][] mat,/* int row, int column,*/ int num)
{
for(int i = 0; i < mat.length; i++) {
for(int j = 0; j<mat[0].length; j++) {
int temp = slopeLength(mat, i, j, num);
if (_longestSlope < temp)
_longestSlope = temp;
}
}
}
private static void checkEach (int[][] mat, int row, int column, int num)
{
int temp;
if (column >= mat[0].length)
{
//if (row >= mat.length)
return;
//else
//checkEach (mat , row +1, 0, num);
}
else
{
temp = slopeLength(mat, row, column, num);
if (_longestSlope < temp)
_longestSlope = temp;
}
checkEach (mat , row, column + 1, num);
}
private static int max (int a , int b)
{
return (a>b)?a:b;
}
}
checkEach方法的第二种实现即使对于很小的矩阵也将返回stackOverFlow