java - Shortest path (fewest nodes) for unweighted graph -


I am trying to create a method that is a non-great graph from one node to another Returns the short cut. I used to consider the use of the dzstra, but it seems a bit because I only want a couple. Instead I have applied a fourth-first discovery, but the problem is that there are some nodes in my return list that I do not want - how can I achieve my goal?

  Public listing & lt; Node & gt; GetDirections (node ​​start, end node) {list & lt; Node & gt; Directions = new linked list & lt; Node & gt; (); From queue & lt; Node & gt; Q = new linked list & lt; Node & gt; (); Node current = start; Q.add (current); While (! Q.isEmpty ()) {current = q.remove (); Directions.add (current); If (current. Angle (finish)) {break; } Else {for (node ​​node: current.getout nodes ()) {if (! Q.contains (node)) {q.add (node); }}}} If (! Current.exls (end)) {System.out.println ("can not access destination"); } Returning directions; } 

Actually your code will not end in cyclical graph, graph 1 -> 2 Consider -> 1. You should have some array where you have already visited the node and you can save the previous nodes for each node, from which you came. So here's the right code:

Private map & lt; Node, boolean & gt;> vis = new hashmap & lt; Node, boolean & gt; (); Private map & lt; Node, node & gt; Prev = new hashmap & lt; Node, node & gt; (); Public list getDirections (node ​​start, node finish) {list directions = new linked list (); Q q = new linked list (); Node current = start; Q.add (current); Vis.put (current, true); While (! Q.isEmpty ()) {current = q.remove (); If (current. Angle (finish)) {break; } Else {for (node ​​node: current.getautonate ()) {if (! Vis.contains (node)) {q.add (node); Vis.put (node, true); Prev.put (node, current); }}}} If (! Current.exls (end)) {System.out.println ("can not access destination"); } (Node node = fin; node! = Null; node = pr. (Node)) {directions.add (node); } Directions.reverse (); Returning directions; }

Comments

Popular posts from this blog

asp.net - Javascript/DOM Why is does my form not support submit()? -

sockets - Delphi: TTcpServer, connection reset when reading -

javascript - Classic ASP "ExecuteGlobal" statement acting differently on two servers -