A method of Java implementation using breadth-first traversal (BFS) to compute the shortest path _java

Source: Internet
Author: User

This paper illustrates the method of using breadth-first traversal (BFS) to compute the shortest path in Java implementation. Share to everyone for your reference. The specific analysis is as follows:

We use strings to represent the vertices of the graph (Vertax) to simulate several locations in school classroom, Square, toilet, canteen, South Gate, North Gate, and then compute the shortest path between any two points.

As shown in the following illustration:

For example, I want to canteen from North Gate, the output of the program should be:

Bfs:from [North Gate] to [canteen]: North
gate
Square
Canteen

First, define an algorithm interface algorithm:

Public interface Algorithm {
  /**
   * Execute algorithm
  /Void Perform (Graph g, String Sourcevertex);
  /**
   * Get the path * *
  map<string, string> GetPath ();
}

Then, define the diagram:

/** * (non-direction) diagram */public class Graph {//diagram's beginning private String firstvertax;
  adjacency table Private map<string, list<string>> adj = new hashmap<> ();
  Traversal algorithm private algorithm algorithm;
  Public Graph (algorithm algorithm) {this.algorithm = algorithm;
  /** * Execute algorithm/public void do () {Algorithm.perform (this, firstvertax); /** * Obtains the shortest path from the starting point to {@code vertex} point * @param vertex * @return/public stack<string> Findpathto (stri
    ng Vertex) {stack<string> Stack = new stack<> ();
    Stack.add (vertex);
    map<string, string> path = Algorithm.getpath (); for (String location = Path.get (vertex); false = = Location.equals (firstvertax); location = Path.get (location)) {s
    Tack.push (location);
    } stack.push (Firstvertax);
  return stack;
      /** * Add an edge */public void Addedge (string Fromvertex, String Tovertex) {if (Firstvertax = null) {
    Firstvertax = Fromvertex; } ADJ.get (Fromvertex). Add (Tovertex);
  Adj.get (Tovertex). Add (Fromvertex);
  /** * Add a vertex */public void Addvertex (String vertex) {adj.put (vertex, New arraylist<> ());
  Public map<string, List<string>> Getadj () {return adj; }
}

Here we use the strategy design pattern, separating the algorithm from the graph class, and selecting the traversal algorithm for graph by passing in an implementation of the algorithm interface when constructing the graph object.

Public Graph (algorithm algorithm) {
    this.algorithm = algorithm;
  }

The storage structure of the graph is adjacency table, where a map is used to represent the adjacency table, the key of the map is the school location (String), and value is a table of places (list<string>) connected to the location.

adjacency table
  Private map<string, list<string>> adj = new hashmap<> ();

Then, write the BFS implementation of the algorithm interface:

/** * Package BFS Algorithm */public class Broadfristsearchalgorithm implements algorithm {//save visited locations private list<string
  > Visitedvertex;
  Save the shortest path private map<string, string> path;  @Override public void Perform (Graph g, String Sourcevertex) {if (null = = Visitedvertex) {Visitedvertex = new
    Arraylist<> ();
    } if (null = = path) {path = new hashmap<> ();
  } BFS (g, Sourcevertex);
  @Override public map<string, string> GetPath () {return path;
    } private void BFS (Graph g, String Sourcevertex) {queue<string> Queue = new linkedlist<> ();
    Mark beginning Visitedvertex.add (Sourcevertex);
    Starting point row Queue.add (Sourcevertex);
      while (false = = Queue.isempty ()) {String ver = queue.poll ();
      list<string> Tobevisitedvertex = G.getadj (). get (ver);
          for (String V:tobevisitedvertex) {if (false = = Visitedvertex.contains (v)) {Visitedvertex.add (v); Path. Put (V, ver);
        Queue.add (v); }
      }
    }
  }
}

Where path is the map type, meaning a path from value to key.

BFS Algorithm Description:

1. Mark the starting point as visited and put into the queue.
2. Take a vertex from the queue and get all the vertices that are connected to the vertex.
3. Traverse these vertices to determine whether the vertex has been visited before, if not, mark the point as accessed, record the current path, and row the current vertex.
4. Repeat 2, 3 until the queue is empty.

Test Cases:

String[] vertex = {"North gate", "South Gate", "classroom", "Square", "toilet", "canteen"};
  Edge[] edges = {
      New Edge ("North Gate", "classroom"),
      New Edge ("North Gate", "Square"),
      New Edge ("classroom" , "toilet"),
      New Edge ("square", "toilet"),
      New Edge ("Square", "canteen"),
      New Edge ("Toilet", "South Gate") ,
      new Edge ("Toilet", "South Gate"),
  };
@Test public
  void Testbfs () {
    graph G = new Graph (new Broadfristsearchalgorithm ());
    Addvertex (g);
    Addedge (g);
    G.done ();
    stack<string> result = G.findpathto ("canteen");
    System.out.println ("Bfs:from [North Gate] to [canteen]:");
    while (!result.isempty ()) {
      System.out.println (Result.pop ());
    }
  }

I hope this article will help you with your Java programming.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.