Note that there are some explanatory texts on larger screens.

plurals
  1. POrecursive search in java
    primarykey
    data
    text
    <p>I have the following problem: I have a hashset of Pairs. Pair is a pair of ints. the pair represents "likes". let's say my set is :&lt;1,2>,&lt;2,1>,&lt;3,1>,&lt;6,7>,&lt;5,7>,&lt;2,6> this means 1 likes 2 and 2 likes 1 and 3 likes 1 and so on...</p> <p>What I'm requested to do is to look at those relations as a graph and given two numbers let's say 2 and 6 I have to find whether there is a route in a graph from 2 to 6 with at most 5 edges connecting between them...</p> <p>how to write a short recursive method that calculates if the route exists? I wrote the following code:</p> <pre><code>private boolean findPath(int from, int to, int count){ System.out.println(from+" "+to+" "+count); if(from==to &amp;&amp; count&lt;=5) return true; if(count&gt;5) return false; Iterator&lt;CookingParty.Pair&gt; iter=likesSet.iterator(); while(iter.hasNext()){ Pair curr=iter.next(); if(curr.likes==from &amp;&amp; curr.liked==to){ return true; } if(curr.likes==from) return findPath(curr.liked, to, count+1); } return false; } </code></pre> <p>the problem is that it won't continue going over the rest of the possibilities once one was found to be wrong. how can I change it to work?</p> <p>this is the update:</p> <pre><code>private boolean findPath(int from, int to, int count){ System.out.println(from+" "+to+" "+count); if(from==to &amp;&amp; count&lt;=5) return true; if(count&gt;5) return false; Iterator&lt;CookingParty.Pair&gt; iter=likesSet.iterator(); boolean found=false; while(iter.hasNext() &amp;&amp; !found){ Pair curr=iter.next(); if(curr.likes==from &amp;&amp; curr.liked==to){ found=true; return found; } if(curr.likes==from) return findPath(curr.liked, to, count+1); } return found; </code></pre> <p>}</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload