Using recursion to find the shortest possible path
807580Sep 8 2009 — edited Sep 11 2009Hi, Im having some difficulty using recursion on a problem of mine.
Suppose you have a robot that is in any position on a grid, i.e. 5,6. the robot has to find the shortest possible way of getting to point 1, 1.
What I cant figure out is how to do a recursive call on a method that would find all of the possible paths to 1, 1 (for this case the robot can only move down and left so if he is at point 5,6 he could only go to point 5, 5, or point 4,6. So what Im trying to figure out is how to call a function that would calculate the possible "moves" from the starting point, and then again from the next destination.
all I can get it to do is calculate essentially one set of moves.
here is what I have, note there is nothing currently stopping this program from running if ikestreet and ikeAvenue dont come to equal 1 at the same time.
This code outputs Ike is on street 3 and Avenue 3Ike is on street 2 and Avenue 21
it should output ike is on street 2, avenue 3, street 1 avenue 3, street 1 avenue 2, ...etc
public class RecursiveIke {
public static void main(String[] args)
{
System.out.print(CountPaths(3,3));
}
public static int CountPaths(int IkeStreet, int IkeAvenue)
{
if (IkeStreet==1 && IkeAvenue== 1){
return 1;
}
else {
System.out.print("Ike is on street " + IkeStreet + " and Avenue " + IkeAvenue);
return (CountPaths(IkeStreet -1, IkeAvenue -1));