Question: I need to implement a method that checks if there is a path between two vertices using Breadth first search. Requirements: Use a LinkedList subtyped
I need to implement a method that checks if there is a path between two vertices using Breadth first search. Requirements:
Use a LinkedList subtyped as the Queue interface when implementing BFS. I have already started working on the method and I'll paste the code down below but feel free to start over completely.
Note that the implementation of the graph is done with adjacency hashmap. If you need to see the class let me know.
import java.util.Arrays; import java.util.Iterator; import java.util.LinkedList; import java.util.Queue; /** * Class for solving graph problems. * * @author [Name] * @version [Date] */ public class GraphAlgorithms { /** * Determines if a component has a cycle. * * @param g the graph to search * @param v the node to start at * @param visited boolean array keeping track of visited nodes * @param parent parent node of v * @return true if component has cycle, false otherwise */ private static boolean DFS(Graph g, int v, boolean[] visited, int parent) { visited[v] = true; for(Iterator it = g.neighbors(v); it.hasNext();){ if(!visited[v] && DFS(g, it.next(), visited,v) ){ return true; } else if(visited[v] && v!=parent){ return true; } } return false; } /** * Determine if there is a cycle in the graph. Implement using DFS. * * @param g the graph to search * @return true if there exists at least one cycle in the graph, false otherwise */ public static boolean hasCycle(Graph g) { int n = g.numVertices(); boolean[] visited = new boolean[n]; for(int v = 0; v < n ; v++){ if(!visited[v] && DFS(g,v,visited,-1 )){ return true; } } return false; } /** * Determine if there is a path between two vertices. Implement using * BFS. * * @param v vertex * @param w vertex * @param g the graph to search * @return true if there is a path between v and w, false otherwise */ public static boolean hasPath(Graph g, int v, int w) { if(v == w){ return true; } Queue queue = new LinkedList<>(); int distance = 0; int n = g.numVertices(); boolean [] visited = new boolean[n]; visited [v] = true; queue.add(v); while (!queue.isEmpty()){ int size = queue.size(); while (size > 0){ } } return false; } } Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
