Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...