Java Program to Check if Path Exists in a Graph

This is a java program to construct a undirected graph and check whether path exists between two vertices, if it exists class return true, false otherwise. Class implements standard Breadth First Search algorithm to traverse from given source node to destination node.

Here is the source code of the Java Program to Find Whether a Path Exists Between 2 Given Nodes. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

  1. //This is a sample program to check that there exists a path between source node and destination node
  2. import java.util.HashMap;
  3. import java.util.LinkedHashSet;
  4. import java.util.LinkedList;
  5. import java.util.Map;
  6. import java.util.Scanner;
  7. import java.util.Set;
  8.  
  9. public class Path_Between_Nodes
  10. {
  11.     private Map<String, LinkedHashSet<String>> map = new HashMap();
  12.  
  13.     public void addEdge(String node1, String node2)
  14.     {
  15.         LinkedHashSet<String> adjacent = map.get(node1);
  16.         if (adjacent == null)
  17.         {
  18.             adjacent = new LinkedHashSet();
  19.             map.put(node1, adjacent);
  20.         }
  21.         adjacent.add(node2);
  22.     }
  23.  
  24.     public void addTwoWayVertex(String node1, String node2)
  25.     {
  26.         addEdge(node1, node2);
  27.         addEdge(node2, node1);
  28.     }
  29.  
  30.     public boolean isConnected(String node1, String node2)
  31.     {
  32.         Set adjacent = map.get(node1);
  33.         if (adjacent == null)
  34.         {
  35.             return false;
  36.         }
  37.         return adjacent.contains(node2);
  38.     }
  39.  
  40.     public LinkedList<String> adjacentNodes(String last)
  41.     {
  42.         LinkedHashSet<String> adjacent = map.get(last);
  43.         if (adjacent == null)
  44.         {
  45.             return new LinkedList();
  46.         }
  47.         return new LinkedList<String>(adjacent);
  48.     }
  49.  
  50.     private static String  START;
  51.     private static String  END;
  52.     private static boolean flag;
  53.  
  54.     public static void main(String[] args)
  55.     {
  56.         // this graph is directional
  57.         Path_Between_Nodes graph = new Path_Between_Nodes();
  58.         // graph.addEdge("A", "B");
  59.         graph.addEdge("A", "C");
  60.         graph.addEdge("B", "A");
  61.         graph.addEdge("B", "D");
  62.         graph.addEdge("B", "E"); 
  63.         graph.addEdge("B", "F");
  64.         graph.addEdge("C", "A");
  65.         graph.addEdge("C", "E");
  66.         graph.addEdge("C", "F");
  67.         graph.addEdge("D", "B");
  68.         graph.addEdge("E", "C");
  69.         graph.addEdge("E", "F");
  70.         // graph.addEdge("F", "B");
  71.         graph.addEdge("F", "C");
  72.         graph.addEdge("F", "E");
  73.         LinkedList<String> visited = new LinkedList();
  74.         System.out.println("Enter the source node:");
  75.         Scanner sc = new Scanner(System.in);
  76.         START = sc.next();
  77.         System.out.println("Enter the destination node:");
  78.         END = sc.next();
  79.  
  80.         visited.add(START);
  81.         new Path_Between_Nodes().breadthFirst(graph, visited);
  82.         sc.close();
  83.     }
  84.  
  85.     private void breadthFirst(Path_Between_Nodes graph,
  86.             LinkedList<String> visited)
  87.     {
  88.         LinkedList<String> nodes = graph.adjacentNodes(visited.getLast());
  89.  
  90.         for (String node : nodes)
  91.         {
  92.             if (visited.contains(node))
  93.             {
  94.                 continue;
  95.             }
  96.             if (node.equals(END))
  97.             {
  98.                 visited.add(node);
  99.                 printPath(visited);
  100.                 flag = true;
  101.                 visited.removeLast();
  102.                 break;
  103.             }
  104.         }
  105.  
  106.         for (String node : nodes)
  107.         {
  108.             if (visited.contains(node) || node.equals(END))
  109.             {
  110.                 continue;
  111.             }
  112.             visited.addLast(node);
  113.             breadthFirst(graph, visited);
  114.             visited.removeLast();
  115.         }
  116.         if (flag == false)
  117.         {
  118.             System.out.println("No path Exists between " + START + " and "
  119.                     + END);
  120.             flag = true;
  121.         }
  122.  
  123.     }
  124.  
  125.     private void printPath(LinkedList<String> visited)
  126.     {
  127.         if (flag == false)
  128.             System.out.println("Yes there exists a path between " + START
  129.                     + " and " + END);
  130.  
  131.         for (String node : visited)
  132.         {
  133.             System.out.print(node);
  134.             System.out.print(" ");
  135.         }
  136.         System.out.println();
  137.     }
  138. }

Output:

$ javac Path_Between_Nodes.java
$ java Path_Between_Nodes
 
Enter the source node:
E
Enter the destination node:
B
No path Exists between E and B
 
Enter the source node:
A
Enter the destination node:
E
Yes there exists a path between A and E
A C E 
A C F E

Sanfoundry Global Education & Learning Series – 1000 Java Programs.

advertisement
advertisement

Here’s the list of Best Books in Java Programming, Data Structures and Algorithms.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.