java - DFS Recursion Woes -


i'm trying write algorithm determine whether 2 nodes in directed graph connected. simple enough, i'm getting hung on recursive implementation of dfs.

my solution, works, quite ugly:

public static boolean isconnected (node src, node dst) {     hashset<node> visited = new hashset<>();     return isconnectedhelper(src, dst, visited); }  private static boolean isconnectedhelper(node src, node dst, hashset<node> visited) {     if (src.equals(dst)) {         return true;     }      if (!visited.contains(src)) {         visited.add(src);         (node neighbor : src.neighbors) {             if (isconnectedhelper(neighbor, dst, visited))                 return true;         }     }     return false; } 

notably, line ugly:

        if (isconnectedhelper(neighbor, dst, visited))             return true; 

is there better way write this? main trouble getting algorithm continue searching if there's miss, stop searching once have match. imagine there's clean way of doing this...?

assuming implementation correct, how look?

public static boolean isconnected (node src, node dst) {     hashset<node> visited = new hashset<>();     return isconnected(src, dst, visited); //same name used, why not? method overloading. }  private static boolean isconnected (node src, node dst, hashset<node> visited) {     if (src.equals(dst)) return true;     if (visited.contains(src)) return false;     visited.add(src);     (node neighbor : src.neighbors) {         if (isconnected(neighbor, dst, visited)) return true;     } } 

Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -