我只是无法得到递归的窍门,尤其是对于复杂的示例。如果有人需要一些时间来解释它,我会非常感激。我从字面上有4张纸满了我追踪这个功能,但我不知道如何把它放在一起。Java中的高级递归
public static String shortestPath(int x, int y, int tX, int tY,boolean blocked[][]) {
if(x>blocked.length-1 || y>blocked[0].length-1 || x<0 || y<0)
return null;
if(blocked[x][y]==true)
return null;
if(x==tX && y==tY)
return "";
String paths[]=new String[4];
blocked[x][y]=true; //this just means this coordinate is blocked, so dont use it
paths[0]=shortestPath(x, y+1, tX, tY, blocked);
paths[1]=shortestPath(x, y-1, tX, tY, blocked);
paths[2]=shortestPath(x+1, y, tX, tY, blocked);
paths[3]=shortestPath(x-1, y, tX, tY, blocked);
blocked[x][y] = false;
int result=findShortestString(paths, 0, 3);
//findShortestString just takes an array of strings,
//with 0 being the lo index and 3 being the hi,
//and returns the index that contains the string with the shortest length.
//5
if(paths[result]==null)
return null;
else{
if(result==0)
return 'N' + paths[result];
if(result==1)
return 'S' + paths[result];
if(result==2)
return 'E' + paths[result];
if(result==3)
return 'W' + paths[result];}
return paths[result];
所以这段代码所做的是什么,给定一个X和Y参数,它告诉你的移动最短的组合,你将不得不作出(NSWE为北,南,西,东),以达到tX和tY参数。代码完美地工作,但我不知道如何。
当我尝试追踪路径[0]计算的路径时,它总是会出现为空,因为y总是会一直增加,直到超出边界,并返回空值。路径[1] [2]和[3]的情况也是如此,它们都返回null,不是吗?那么,这个功能是如何工作的?
可能的重复[理解Java中的递归更好一点](http://stackoverflow.com/questions/4170207/understanding-recursion-in-java-a-little-better) – EJP 2010-11-13 08:50:07