I found a couple of ways to improve your program speed by significant amounts.
Test methodology
First, I ran your original function using a 14x15 matrix. I ran it two times in a row in the same run and timed the second run. It took 31.19 seconds on my machine. I used that as the baseline time to beat.
Use ArrayList instead of HashSet
I'm not sure why you chose to use a HashSet as the container to build your results. Since we are going to presumably just print out all the results sequentially, an ArrayList would be faster because it avoids any unnecessary hashing.
After switching the HashSet to an ArrayList, the time went from 31.19 to 12.80 seconds (2.4x faster).
Using a char [] instead of a String
You can speed up your program by using a char array instead of a String as your temporary string that you build. Something like this:
static public void findPaths (char [] tempPath, int i, int j, int m,
int n, char [][] arr, ArrayList<String> results) {
tempPath[i+j] = arr[i][j];
if (i == m -1 && j == n-1) {
results.add(new String(tempPath));
return;
}
//right
if (j+1 < n) {
findPaths (tempPath, i, j+1, m, n, arr, results);
}
//down
if (i+1 < m) {
findPaths (tempPath, i+1, j, m, n, arr, results);
}
}
You must call the function initially with a char array of size m+n-1
. A lot of time in the original function is being spent creating temporary strings. This method avoids all the intermediate strings and only creates the strings that appear in the output.
After switch to a char [] as a temp, the time went from 12.80 to 7.30 seconds (1.75x faster).
Other things I tried that didn't make any difference
I tried a couple of other things that ended up not making any difference in the time.
I added "short circuiting" to the code. When either i
or j
reaches its limit, you can handle that case specially and immediately reach the final cell instead of continuing to recurse.
I converted the recursive function into an iterative one.
Both of the above neither hurt nor helped the final time.
m
andn
... they never change? Can you give some example input and output? I suspect there is a much better solution to this, if I am right about the guesses I have about the missing details.... \$\endgroup\$