We use strings to represent the vertices of the graph (Vertax) to simulate several locations in the school classroom, Square, toilet, canteen, South Gate and North Gate, and then calculate the shortest path between any two points.
For example, I want to go to canteen from North Gate, the output of the program should be:
BFSFrom[North Gate]to[Canteen]: NorthGate Square Canteen
First define an algorithm interface Algorithm
:
publicinterface Algorithm { /** * 执行算法 */ void perform(Graph g, String sourceVertex); /** * 得到路径 */ Map<String, String> getPath();}
Then, define the diagram:
/** * (no direction) chart * * Public class Graph { //The starting point of the graph PrivateString Firstvertax;//adjacency table Privatemap<string, list<string>> adj =NewHashmap<> ();//Traversal algorithm Privatealgorithm algorithm; Public Graph(Algorithm algorithm) { This. algorithm = algorithm; }/** * Execution algorithm * / Public void Done() {Algorithm.perform ( This, Firstvertax); }/** * Get the shortest path from the starting point to {@code vertex} points * @param vertex * @return * * PublicStack<string>Findpathto(String Vertex) {Stack<string> Stack =NewStack<> (); Stack.add (vertex); map<string, string> path = Algorithm.getpath (); for(String location = Path.get (vertex);false= = Location.equals (firstvertax); Location = Path.get (location)) {Stack.push); } stack.push (Firstvertax);returnStack }/** * 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,NewArraylist<> ()); } PublicMap<string, list<string>>Getadj() {returnAdj }}
Here we use the strategy design pattern to separate the algorithm from the graph class, and to select the traversal algorithm by passing in an Algorithm
implementation of the interface when constructing the graph object Graph
.
publicGraph(Algorithm algorithm) { this.algorithm = algorithm; }
The storage structure of the graph is an adjacency table, where the Map
map key is the school location ( String
), and value is a table of places () that is connected to the location List<String>
.
// 邻接表 privateMap<StringList<String>>=new HashMap<>();
Then, write Algorithm
the BFS implementation of the interface:
/** * Package BFS algorithm * / Public class broadfristsearchalgorithm implements algorithm { //Save locations that have been visited PrivateList<string> Visitedvertex;//Save Shortest Path Privatemap<string, string> Path;@Override Public void Perform(Graph G, String Sourcevertex) {if(NULL= = Visitedvertex) {Visitedvertex =NewArraylist<> (); }if(NULL= = Path) {Path =NewHashmap<> (); } BFS (g, Sourcevertex); }@Override PublicMap<string, string>GetPath() {returnPath }Private void BFS(Graph G, String Sourcevertex) {Queue<string> Queue =NewLinkedlist<> ();//Mark startVisitedvertex.add (Sourcevertex);//Starting point into rowQueue.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, which means a path from value to key.
BFS Algorithm Description:
1. Mark the start point as accessed and put into the queue.
2. Remove a vertex from the queue and get all the vertices that are connected to the vertex.
3. Traverse these vertices to determine if the vertex has been accessed, if no, mark the point as accessed, record the current path, and into row the current vertex.
4. Repeat 2, 3 until the queue is empty.
Test Case:
String[] vertex = {"North Gate","South Gate","Classroom","Square","Toilet","Canteen"}; Edge[] edges = {NewEdge ("North Gate","Classroom"),NewEdge ("North Gate","Square"),NewEdge ("Classroom","Toilet"),NewEdge ("Square","Toilet"),NewEdge ("Square","Canteen"),NewEdge ("Toilet","South Gate"),NewEdge ("Toilet","South Gate"), };
@Test publicvoidtestBFS() { 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()); } }
Using breadth-first traversal (BFS) to calculate the shortest path-Java implementation