2011-12-10 139 views
0

我有以下问题: 我有一个对的哈希集。 Pair是一对整数。这对表示“喜欢”。 假设我的设置是:< 1,2>,< 2,1>,< 3,1>,< 6,7>,< 5,7>,< 2,6> 这意味着1喜欢2和2喜欢1和3喜欢1等等......java中的递归搜索

我被要求做的是把这些关系看作一个图并给出两个数字让我们说2和6我必须找出是否有路线在从2到6的图中,最多连接5条边...

如何编写计算路由是否存在的短递归方法? 我写了下面的代码:

private boolean findPath(int from, int to, int count){ 
    System.out.println(from+" "+to+" "+count); 
    if(from==to && count<=5) 
     return true; 
    if(count>5) 
     return false; 
    Iterator<CookingParty.Pair> iter=likesSet.iterator(); 
    while(iter.hasNext()){ 
     Pair curr=iter.next(); 
     if(curr.likes==from && curr.liked==to){ 
      return true; 
     } 
     if(curr.likes==from) 
      return findPath(curr.liked, to, count+1); 

    } 

    return false; 
} 

的问题是,它不会继续去在的可能性休息一次,一个被认为是错误的。 我该如何改变它的工作?

这是更新:

private boolean findPath(int from, int to, int count){ 
System.out.println(from+" "+to+" "+count); 
    if(from==to && count<=5) 
     return true; 
    if(count>5) 
     return false; 
    Iterator<CookingParty.Pair> iter=likesSet.iterator(); 
    boolean found=false; 
    while(iter.hasNext() && !found){ 
     Pair curr=iter.next(); 
     if(curr.likes==from && curr.liked==to){ 
      found=true; 
      return found; 
     } 
     if(curr.likes==from) 
     return findPath(curr.liked, to, count+1); 

    } 

    return found; 

}

+0

这是什么意思?这意味着我需要更好地设置我的问题的格式? – mary

+0

你是否有任何代码我们都希望别人为你做所有的工作? – Marthin

+2

@mary它在这里是习惯在stackoverflow点击接受你选择的答案是正确的你的问题。它为这里的其他人试图帮助他人提供了激励。 – buruzaemon

回答

1

为你找到一个对,其中curr.likes == from目前你作为很快就会回来。若要探索其他路径,则不能立即在while循环中返回,但在尚未找到路径时,请检查其他可能性。

boolean found = false; 
while(iter.hasNext() && !found){ 
    // check a path 
} 
return found; 

重新更新:您仍然在循环中返回。在你找到路径的情况下,没关系,但绝对不能在一般情况下返回。如果curr.likes == fromcurr.liked != to,请检查路径并更新布尔型,不要返回。循环结束后返回。

+0

它仍然不起作用。 – mary

+0

那么,现在循环体是什么?如果它包含“return”或不包含“||”,则可能是错误的。 –

+0

更新是在问题的主体 – mary