All possible paths

public class AllPath {
	
	public static void main(String[] args) {
		int[][] matrix = new int[3][3];
		/*int[][] matrix = {
				{0,0,0,0},
				{0,1,0,0},
				{0,0,1,0}
		};*/
		ArrayList<ArrayList<Pair>> result = findAllPath(matrix);
		for(ArrayList<Pair> s : result) {
			for(Pair p : s) {
				System.out.print("(" + p.x + ", " + p.y + ")-->");
			}
			System.out.println();
		}
	}
	public static ArrayList<ArrayList<Pair>> findAllPath(int[][] matrix) {
	    return help(0, 0, matrix);
	}

	public static ArrayList<ArrayList<Pair>> help(int m, int n, int[][] matrix) {
	    ArrayList<ArrayList<Pair>> result = new ArrayList<ArrayList<Pair>>();
	    Pair pair = new Pair(m, n);
	    //this  is used for meet some obstacles
	    //if(matrix[m][n] == 1) return result;
	    
	    //end of the backtracing, when is the end point
	    if(m == matrix.length - 1 && n == matrix[0].length - 1) {
	        ArrayList<Pair> sub = new ArrayList<Pair>();
	        sub.add(pair);
	        result.add(sub);
	        return result;
	    }else {
	    	if(n != matrix[0].length - 1){
		        for(ArrayList<Pair> s : help(m, n + 1, matrix)) {
		            s.add(0, pair);
		            result.add(s);
		        }
	    	}
	    	if(m != matrix.length - 1){
		        for(ArrayList<Pair> s : help(m + 1, n, matrix)) {
		            s.add(0, pair);
		            result.add(s);
		        }
	    	}
	    }
	    return result;
	}
}

class Pair{
    int x;
    int y;
    public Pair(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章