我有以下问题: 我有一个对的哈希集。 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;
}
这是什么意思?这意味着我需要更好地设置我的问题的格式? – mary
你是否有任何代码我们都希望别人为你做所有的工作? – Marthin
@mary它在这里是习惯在stackoverflow点击接受你选择的答案是正确的你的问题。它为这里的其他人试图帮助他人提供了激励。 – buruzaemon