Using recursion to calculate a path through an array
I've got an assignment that says to "take a number (size of grid - no larger than 10) and a starting location and an ending location and recursively computes all of the NorthEast paths." I'm having trouble wrapping my head around how to do this... Here's what I have so far. (I know it's not much code, I've been working on paper mostly trying to work this out.
Code :
import java.util.*;
import java.io.*;
public class prog2
{
public static void main(String[] args) throws FileNotFoundException
{
File paths = new File("prog2.dat");
Scanner input = new Scanner(paths);
int gridSize = input.nextInt();
boolean[][] grid = new boolean[gridSize][gridSize]; //creates 2D array
}
public static int input(boolean[][] grid)
{
return ;
}
}
My prog2.dat file has exactly this in it:
5
3 0
1 3
Meaning that the array is to be 5x5, which I've got. And I know that the start/end points are 3,0 and 1,3. The problem I'm having is figuring out how to code that.
In the end, it's going to output a list of paths to get from start to end.
I'd like some help with the syntax of what I'm trying to do... I'm also slightly confused by how to pass my array to my other methods.
Thanks, guys!
Re: Using recursion to calculate a path through an array
Define "Northeast paths".
"take a number (size of grid - no larger than 10) and a starting location and an ending location"
As a parameter?
Recursion is used like this:
Code java:
public int factorial(int number)
{
if (number == 0)
return 1;
else
return (number * factorial(number -1));
}
passing arrays to methods:
int value = input(grid);
Just use the name of the array variable to pass.
Re: Using recursion to calculate a path through an array
jpettigrew: I'm assuming this is for Strader's 202?
What you need to do is set up a recursive function, say called findNortheastPath().
Inside the recursive function, you'll need a base case, which would need to basically check to see if the current location (x,y) you are checking is the same as the ending location, if it is return true. If this is not true, the function would need to recursively call the same function twice, but with different starting locations:
1. For going north (x-1, y)
2. For going east (x, y+1)
You can provide output in the recursive function to print out the coordinates as you follow the paths to the ending location.
I know this is vague, but I hope this helps.