简体   繁体   中英

How can I implement a Breadth first search of a graph using Java?

I need to do this using a text file which contains a linked list of the graph which would be, (AEDB), (EA), (DA), (BAC), (CB), Then I ask the user for the node to start at and then the BFS order prints? I know one way to start would be to create a linked list then hash the linked list in a dictionary but don't know from there on, also a node can't be visited more than once. My linked list is something like, HashMap> L = new HashMap>();

    LinkedList<String> listA = new LinkedList<String>();
    listA.add("B"); 
    listA.add("E");

    L.put("A", listA);

    LinkedList<String> listB = new LinkedList<String>();
    listB.add("A");
    listB.add("C");
    listB.add("F");

    L.put("B", listB);

    LinkedList<String> listE = new LinkedList<String>();
    listE.add("A");
    listE.add("F");

    L.put("E", listE);

    LinkedList<String> listF = new LinkedList<String>();
    listF.add("E");
    listF.add("K");
    listF.add("B");

    L.put("F", listF);

    LinkedList<String> listK = new LinkedList<String>();
    listK.add("F");
    listK.add("C");

    L.put("K", listK);

    LinkedList<String> listC = new LinkedList<String>();
    listC.add("K");
    listC.add("B");

    L.put("C", listC);

The output would print the nodes starting from the user inputted one in a breadth first order, but this is as far as I have gotten

What you have used here is called an Adjacency list .

Here is an implementation of BFS which uses an adjacency list like the one you have mentioned above and does a BFS. It prints the visited vertices in a BFS traversal.

public static void BFS(HashMap<String, LinkedList<String>> adjLst, String start) {
    Queue<String> queue = new ArrayDeque<>();
    HashSet<String> seen = new HashSet<>();
    queue.add(start);
    while(0 != queue.size()){
        String vertex = queue.poll();
        if(!seen.contains(vertex)){
            System.out.print(vertex + " ");
            queue.addAll(adjLst.get(vertex)); // Add all neighbors of 'vertex' to the queue
            seen.add(vertex);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM