Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

problem of matrix in java only use recursion

hey guys can someone help me with a question in recursion i need to write a method that uses recursion the method get param metrix and int k(k is the number of turn i can do to get from the first mat[0][0] to the last mat[i.length-1][j.length-1] a turn is If you go right and immediately afterwards down or down and immediately afterwards right) the method needs to return how many possible routes there are with K turns,you can go only down or right.

public static int solutions(int[][]a,int k){
        int path1 = 0 , path2 = 0;

            path1 = solutions(a,k,1,0,0,0);

            path2 = solutions(a,k,0,1,0,0);
        return path1+path2;
    }

    private static int solutions(int[][]a,int k,int i,int j,int previ,int prevj) {


        if (i == a.length - 1 && j == a[j].length - 1 && k == 0) {
            if (k == 0)
                return 1;
            else
                return 0;
        }

        int path1 = 0, path2 = 0 ;  
     if (i < a.length - 1) {
        if (i != previ && j != prevj) {
            if (k > 0)
                path1 = solutions(a, k - 1, i + 1, j, previ, prevj);
                else
            path1 = solutions(a, k, i + 1, j, previ, prevj);
        }
    }
        if (j < a[j].length - 1) {
        if (i != previ && j != prevj) {
            if (k > 0)
                path2 = solutions(a, k - 1, i, j + 1, previ, prevj);
            else
                path2 = solutions(a, k, i, j + 1, previ, prevj);
        }
    }
        return path1 + path2;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...