/* * Finding a path in a graph * * path(X,Y) :- edge(X,Y). * path(X,Y) :- edge(X,Z), path(Z,Y). * */ import java.util.ArrayList; public class Path { static private int[][] tree = { {0,1,0,0,0,0}, // 0->1 {0,0,1,0,1,0}, // 1->2, 1->4 {0,0,0,1,1,0}, // 2->3, 2->4 {0,0,0,0,1,0}, // 3->4 {0,0,0,0,0,1}, // 4->5 {0,0,0,0,0,0} }; public static void main (String[] args) { System.out.println(findPath(0,5)); } public static boolean findPath(int x, int y) { boolean found = false; if (tree[x][y]==1) { System.out.println(x + " -> " + y); found = true; } else { int z; for (z=0; !found& z " + z); } } return found; } } /* Modifications: * Use an ArrayList for collecting the path static ArrayList path = new ArrayList(); path.add(0,y); // base case path.add(0,z); // recursive call * Avoid infinite loops. Mark passed nodes (add tree[x][z]=2 before the recursive call) * * */