Counting possible coordinate moves with recursion
I'm trying to write a method that does the following:
public class GridCounting {
/** Returns the total number of possible routes (paths) from
* (x,y) to (tx,ty).
* There are only three valid kinds of moves:
* Increment x by one.
* Increment x by two.
* Increment y by one.
*
* Hint: You'll need to two base cases.
*/
public static int count(int x,int y, int tx, int ty) {
if (x==tx && y==ty)
return 1;
if (x>tx || y>ty)
return 0;
if (x<tx)
return 1 + count(x+1, y, tx, ty);
if (x<tx) //if x is still less, then we can do another move
return 1 + count(x+2, y, tx, ty);
if (y<ty){
return 1 + count(x, y+1, tx, ty);
}
return 0;
}
}
The trouble that I'm having is that I'm always off by +1. It expects 4 but I give it 5. The confusing part is that if I feed the function cou开发者_如何学Pythonnt(10,15,10,15), then that still counts as 1 move. I dont know how to account for this.
Also y++ then x++ counts as 1 move, and x++ then y++ counts as another move. Edit: Fixed code:
public static int count(int x,int y, int tx, int ty) {
if (x==tx && y==ty)
return 1;
if (x>tx || y>ty)
return 0;
if (x<tx)
return count(x+1, y, tx, ty) + count(x+2, y, tx, ty) + count(x,y+1,tx,ty);
if (y<ty) {
return count(x, y+1, tx, ty); // what does this do?
}
return 0;
}
The trouble that I'm having is that I'm always off by +1. It expects 4 but I give it 5.
In position (x, y)
we, generally speaking, have three choices (x+=1
, x+=2
, y+=1
). Each of them produces separate paths and we need to find how many paths there're in total.
So, this part is wrong
if (x<tx)
return 1+ count(x+1, y, tx, ty);
if (x<tx)
return 1+ count(x+2, y, tx, ty);
if (y<ty){
return 1+ count(x, y+1, tx, ty);
}
return 0;
That was a hint, let me know if you need more.
Also y++ then x++ counts as 1 move, and x++ then y++ counts as another move.
Well, that sounds like two different paths to me.
edit
Ok, return count(x + 1, y, tx, ty) + count(x + 2, y, tx, ty) + count(x, y + 1, tx, ty);
is all you need.
If there're 3 paths starting with first move x + 1
, 2 paths starting with first move x + 2
and 2 paths starting with first move y + 1
, then, obviously, there're 3 + 2 + 2
paths total.
You sure this line is right?
if (x==tx && y==ty)
return 1;
It seems like it should return zero.
On a phone so I can't test it.
if (x==tx && y==ty) return 1;
doesn't sound correct. If you're already at the destination, there are no more routes.
Maybe I not understanding the rules, but I think it's that first base case that's causing your problem. If you're already at the location then you're not making a move.
精彩评论