首页 > 解决方案 > 使用递归的多维度斜率

问题描述

那是多维数组:

{ 3 13 15 28 30} ,
{55 54 53 27 26} ,
{54 12 52 51 50} ,
{50 10  8 53 11} , 

输出应该是if num = 1 : 6,因为从 [1][0] 到 [1][2] 它的 3 然后从 [2][2] 到 [2][3] 它的 2 所以它将是 6 ,num它的斜率用户想要,斜率可以向右或向下,禁止使用任何类型的循环,只能递归,尝试了 8 个小时来解决它,但我很困惑,这是我的代码:

private static int longestSlope (int [][] mat, int num , int i , int j , int count , int temp,int oldi,int oldj,boolean found) 
    {
        System.out.println("oldi " +oldi);
        System.out.println("oldj " +oldj);
        System.out.println("temp " +temp);
        System.out.println("count "+count);
        System.out.println("i "+i);
        System.out.println("j "+j);


        if(i == mat.length-1 && j == mat[0].length-1)
            return count;

        if(i != mat.length && j != mat[0].length) 
        {               

                if(j < mat[0].length-1 && mat[i][j] - num == mat[i][j+1] ) // keep j+
                {

                    if(temp == 0)
                    {
                        found = true;
                        oldj = j;
                        oldi = i;
                    }
                        System.out.println("check2");
                    if(j == 0)
                        temp = longestSlope(mat,num,i,j+1,count,temp+1,oldi,oldj,found);
                    else
                        temp = longestSlope(mat,num,i,j+1,count,temp+1,oldi,oldj+1,found);


                }
                else if(i < mat.length-1 && mat[i][j] - num == mat[i+1][j])
                {

                    if(temp == 0)
                    {
                        found = true;
                        oldj = j;
                        oldi = i;
                    }
                    temp = longestSlope(mat,num,i+1,j,count,temp+1,oldi,oldj,found);
                }
                else if(j < mat[0].length-1)
                    temp = longestSlope(mat,num,i,j+1,count,temp,oldi,oldj,found);
                else if(found)
                {
                    System.out.println(found);
                    System.out.println("found i "+i);
                    System.out.println("found j "+j);
                    found = false;
                    if(j != mat[0].length-1)
                        temp = longestSlope(mat,num,oldi,oldj,count,0,oldi,oldj,found);
                    else if(j == mat[0].length-1 && temp != 0)
                        temp = longestSlope(mat,num,oldi,oldj,count,0,oldi,oldj,found);
                    else
                        temp = longestSlope(mat,num,oldi+1,0,count,0,oldi,oldj,found);
                }
            }


            if(i < mat.length-1 && !found)
            {

                System.out.println("oldj222222222 "+oldj);
                return longestSlope(mat,num,i+1,0,count,0,0,0,found);
            }
            return 0;           

    }

标签: javaarraysrecursion

解决方案


推荐阅读