0

I am attempting to find the shortest path in a route between two points. My adjacency list seems to be correct but the breadth-first search seems to be messing up somewhere. If no path exists between two points in the graph, "Not found" is printed. My code never seems to enter this for some reason, even if it should. My basic understanding of the BST algorithm is making this problem extremely hard to diagnose. I've spent countless hours modifying the code and watching videos but have remained unsuccessful.

I am reading the route data from a text. This part is working perfectly, therefore I feel like it would be redundant to include. What I will say is that the adjacency list my graph code creates looks correct, so it's likely an issue with my BFS function.

class Graph {

// We use Hashmap to store the edges in the graph
private Map<String, List<String> > map = new HashMap<>();

public void BFS(String start, String stop) {
    Queue<String> queue = new ArrayDeque<>();
    HashSet<String> seen = new HashSet<>();
    ArrayList<String> network = new ArrayList<>();
    queue.add(start);
    while(0 != queue.size()){
        String vertex = queue.poll();
        if(!seen.contains(vertex)){
            network.add(vertex);
            queue.addAll(map.get(vertex)); // Add all neighbors of 'vertex' to the queue
            seen.add(vertex);
        }
    }
    
    if (network.contains(stop)) {
        System.out.println("Route Path: ");
        for(String location: network) {
            if (location.equals(stop)) {
                System.out.println(location);
                break;
            } else {
                System.out.println(location + " -> ");
            }
        
        }
    } else {
        System.out.println("Not found.");
    }
}

public void printMap() {
    for(String item: map.keySet()) {
        System.out.println(map.get(item));
    }
}


// This function adds a new vertex to the graph
public void addVertex(String s)
{
    map.put(s, new LinkedList<String>());
}

// This function adds the edge
// between source to destination
public void addEdge(String source,
                    String destination,
                    boolean bidirectional)
{

    if (!map.containsKey(source))
        addVertex(source);

    if (!map.containsKey(destination))
        addVertex(destination);

    map.get(source).add(destination);
    if (bidirectional == true) {
        map.get(destination).add(source);
    }
}

// This function gives the count of vertices
public void getVertexCount()
{
    System.out.println("The graph has "
                    + map.keySet().size()
                    + " vertex");
}

// This function gives the count of edges
public void getEdgesCount(boolean bidirection)
{
    int count = 0;
    for (String v : map.keySet()) {
        count += map.get(v).size();
    }
    if (bidirection == true) {
        count = count / 2;
    }
    System.out.println("The graph has "
                    + count
                    + " edges.");
}

// This function gives whether
// a vertex is present or not.
public boolean hasVertex(String s)
{
    if (map.containsKey(s)) {
        return true;
    }
    else {
        return false;
    }
}

// This function gives whether an edge is present or not.
public boolean hasEdge(String s, String d)
{
    if (map.get(s).contains(d)) {
        return true;
    }
    else {
        return false;
    }
}

// Prints the adjancency list of each vertex.
@Override
public String toString()
{
    StringBuilder builder = new StringBuilder();

    for (String v : map.keySet()) {
        builder.append(v.toString() + ": ");
        for (String w : map.get(v)) {
            builder.append(w.toString() + " ");
        }
        builder.append("\n");
    }

    return (builder.toString());
}

If my question is lacking in any way, please provide constructive feedback so I can make better posts in the future. I can refine my post and supply further information if needed.

M.M.
  • 19
  • 2
  • 1
    What does it do when it should return "No path exists"? Returns a wrong path? Returns something else? or continues infinitely? – user1984 Nov 05 '21 at 22:00
  • If no path exists in the graph, "Not found" should be printed. If a path is found, the shortest path should be printed. To my understanding, the shortest path should be contained in the network ArrayList. If the ArrayList does not contain the stop string, no path exists. – M.M. Nov 05 '21 at 22:06
  • No, I'm asking what it does instead of printing "Not found" when it should do that. That was the problem with the algorithm as I understand from your post. Does it produce a wrong path? Does it loop infinitely? – user1984 Nov 05 '21 at 22:08
  • 1
    This guy makes the best tutorials on the web about algorithms, try it https://youtu.be/oDqjPvD54Ss – Arthur Klezovich Nov 05 '21 at 23:24
  • To make your code an [mre] please add a `main` with test data. Also, explain what is the expected result. The post can benefit from some code formatting. – c0der Nov 06 '21 at 10:33
  • There are a few essential parts missing: when a node (string) is `poll`ed define all its neighbors and add them to the queue. To define the neighbors you need to define the valid manipulation to (for example swap two letters) to get a neighbor. – c0der Nov 06 '21 at 12:15

0 Answers0