我有以下问题: 我有一个对的hashset。对是一对整数。这对代表“喜欢”。 假设我的集合是:< 1,2>,< 2,1>,< 3,1>,< 6,7>,< 5,7>,< 2,6> 这意味着1喜欢2和2喜欢1和3喜欢1等等......
我要求做的是将这些关系看作图形并给出两个数字让我们说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 :(得分:1)
要在图表中搜索路径,您可以使用Depth-First或广度优先搜索。 Depth-first传统上是递归的,因为它使用堆栈。看看这里的伪代码:
答案 1 :(得分:1)
目前,只要找到curr.likes == from
对,就会立即返回。要探索其他路径,您不能立即返回while循环,但是当您还没有找到路径时,请检查更多可能性。
boolean found = false;
while(iter.hasNext() && !found){
// check a path
}
return found;
重新更新:您仍然在循环中返回。在你找到路径的情况下没问题,但在一般情况下绝对不能返回。如果curr.likes == from
和curr.liked != to
,请检查路径并更新布尔值,不要返回。循环结束后返回。