Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8323259
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 8, 20262026-06-08T23:40:06+00:00 2026-06-08T23:40:06+00:00

I am working on a project for school that requires us to find the

  • 0

I am working on a project for school that requires us to find the shortest path between two points. Basically I use a breadth first search to traverse the graph and then use a map to keep track of each cities predecessor. My idea is then that when I reach the end I will then use the edges map to find out how a city was gotten to and essentially work backwards. However when I attempt to pull values from the map all I get is null, even though when I print out the contents it shows that there is something there. If somebody could help me track down the problem I would appreciate it.

Contents of input file with each city and its neighbor:

basic
Bismark      Fargo
Minneapolis  Chicago
StPaul       Chicago
Minneapolis  StPaul
Minneapolis  Fargo
Fargo        GrandForks

The code (corrected version, so this code won’t exhibit the described problem any more):

import java.util.*;
import java.io.*;

public class BFSBasics {
    public static void main(String[] args) throws FileNotFoundException {
        Map<String, List<String>> graph = new HashMap<>();
        openFile(graph, args[0]);
        String start = args[1];
        String end = args[2];

        BFS(graph, start, end);
    }

    public static void openFile(Map<String,List<String>> graph, 
            String file) 
            throws FileNotFoundException{
        Map<String,List<String>> aGraph = new HashMap<>();
        try (Scanner scan = new Scanner(new File(file))){
            if(!scan.next().equals("basic")){
                System.err.println("File cannot be read.");
                System.exit(1);
            }else{
                while(scan.hasNext()){
                    String city1 = scan.next();
                    String city2 = scan.next();
                    addEdge(graph, city1, city2);
                    addEdge(graph, city2, city1);                   
                }   
            }   
        }
    }

    private static void addEdge(Map<String, List<String>> graph, String city1,
            String city2){
        List<String> adjacent = graph.get(city1);
        if(adjacent == null){
            adjacent = new ArrayList<>();
            graph.put(city1, adjacent);
        }
        adjacent.add(city2);
    }

    public static void BFS(Map<String, List<String>> graph, String start,
            String end) {
        boolean done = false;
                //cities that still need to be worked on
        Queue<String> work = new ArrayDeque<>();
                //cities that have already been seen
        Set<String> seen = new HashSet<>();
                //cities predecessor i.e. how it was gotten to
        Map<String, String> edges = new HashMap<>();
        LinkedList<String> path = new LinkedList<>();

        String city = start;
        work.add(start);
        while (!done && !work.isEmpty()) {
            city = work.remove();
            for (String s : graph.get(city)) {
                if (!seen.contains(s)) {
                    edges.put(s, city);
                    work.add(s);
                    seen.add(s);
                    if (s.equals(end)) {
                        done = true;
                    }
                }
            }
        }

        //Work backwards through the edges map and push onto the path stack
        path.push(end);
        String temp = edges.get(end);
        while(!temp.equals(start)){
            path.push(temp);
            temp = edges.get(path.peek()};
        }
        path.push(start);
        //print out the path
        while(!path.isEmpty()){
            System.out.println(path.pop());
        }
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-08T23:40:07+00:00Added an answer on June 8, 2026 at 11:40 pm

    There is something wrong with your path building code:

    path.push(end);                 // push node (n - 1)
    String temp = edges.get(end);   // temp = node (n - 2)
    while(!temp.equals(start)){
        path.push(edges.get(temp)); // push node (n - 3) down to and including node 0
        temp = path.peek();         // temp = node (n - 3) down to and including node 0
    }
    path.push(start);               // push node 0
    

    So the node (n – 2) will never be pushed to the path, whereas the node 0 will be pushed twice.

    But except for this, the program works for me. So perheaps you really have an unreachable target, as Hbcdev suggests. You should check whether or not you actually reached the end node. Note that your graph datra structure models a directed graph, so if you want to interpret your input as undirected edges, you’ll have to insert two directed edges for each line of input.

    Also note that you don’t mark the initial node as seen, whereas all other nodes will get marked as seen when you add them to the queue. You should mark the first as well.

    Edit:
    After you pasted your (almost) complete code, I fixed it in the following ways:

    • added two wildcard imports, for java.util.* and java.io.*. Wildcard imports are quick and dirty.
    • Added a closing } at the very end to close the class definition.
    • Added a line with the word basic to your input data. You really should System.exit(1) in case of that keyword missing, instead of continuing with inconsistent state.

    With those modifications, I tested all possible combinations of two cities, always in both orders, and including paths form a city to itself. No evidence of null values anywhere, neither in output nor as a cause of printed exceptions.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm working on a school project that requires me to parse a BNF grammar.
I am working on a school project (if you couldn't figure that out just
Im working on a school project and it's my first time on android development.
I am working on a school project that uses ASP.NET. I found this TextEditor
My question is about a school project that I'm working on. It involves mapping
I'm working on a school project where I am required to use the GNU
I am currently working on a project for school that is a java memo
I'm working on a project for school and the instructor insists that all code
I'm working on a project for school, we use visual studio 2008 there and
I'm working on a school project, and basically we're trying to learn about stack

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.