python,algorithm,graph,graph-theory,dijkstra

Dijkstra algorithm always finds the shortest path (in graphs without negative edges) and never backtracks. It is easy to reason about it. Always choosing the minimum Think about a node and its edges (it's just part of a larger graph): 6 _ 3 | / 14| /9 |/ 1-------2 7...

In a.push_back(&q); you are storing the address of a local object, which will cease to exist once the function terminates....

It sounds like you’re taking the shortest path from wherever you find yourself currently, and not calculating the total distance to get to a node. Let’s step through it in detail. Dijkstra’s algorithm sets up two sets of nodes: visited (with known distances) and unvisited (with tentative distances). We start...

In a d-ary heap, up-heaps (e.g., insert, decrease-key if you track heap nodes as they move around) take time O(log_d n) and down-heaps (e.g., delete-min) take time O(d log_d n), where n is the number of nodes. The reason that down-heaps are more expensive is that we have to find...

c++,algorithm,data-structures,dijkstra

You are missing out this step: Vertex v = smallest unknown distance vertex; and instead looping through all vertices. The distance to the starting vertex is initialized to 0 so if you implement this part of the algorithm and pick the v with the smallest distance that is not "known"...

c++,multidimensional-array,dijkstra,shortest-path,adjacency-matrix

Converting an image into an adjacency matrix is completely unnecessary; the only thing you need is the "neighbor-ness" information which is already implicitly present. The neighbors of any pixel i,j are represented by the pixels at (i-1,j), (i+1,j), (i,j-1), (i,j+1) subject to image boundaries. You don't need a matrix to...

algorithm,graph,dijkstra,shortest-path,breadth-first-search

This is laborous case work: A < B and 0 and N-1 are joined by A -> trivial. B < A and 0 and N-1 are joined by B -> trivial. B < A and 0 and N-1 are joined by A -> Do BFS on graph with only K...

algorithm,graph,dijkstra,shortest-path

If you look at the pseudocode from the Wikipedia link you gave, you'll see an array in there called prev[]. This array contains, for each node v in the graph, the previous node u in the shortest path between the source node s and v. (This array is also called...

java,traversal,dijkstra,shortest-path,maze

All I can see from looking at your code is that you're not mainlining your state properly. You have a method called moveToPosition() but it's called for every node - and you end up adding every x/y combination to the paths List. To be honest a lot of this doesn't...

java,algorithm,gis,dijkstra,a-star

Represent each node as a bunch of nodes, one for each incoming road. So let us have the following graph. And let use the following rules: If Came to B from A than we can only turn to D If Came to B from C than we can only go...

c++,graph,compiler-errors,pass-by-reference,dijkstra

I´m assuming assignWeights is not part of the Graph class. Passing by reference/value/anything isn´t the problem here, but you´re confusing your different VertexTypes. a) You have a function void assignWeights(Graph<string> &dGraph, int numVertices, VertexType myVertices[], int startingLocation, Queue<string>& getTo) where VertexType is a class, struct, or typedef somewhere else. b)...

java,arrays,indexoutofboundsexception,dijkstra

for (int i = 0; i <= myNodes.size(); i++) This causes the problem change it to for (int i = 0; i < myNodes.size(); i++) Because, lets say myNodes.size() returns 8 and you are trying to reach dist[8] but dist[] array starts at 0 and ends at 7....

algorithm,dijkstra,directed-acyclic-graphs

Consider the graph (directed 1 -> 2, 2-> 4, 4 -> 3, 1 -> 3, 3 -> 5): 1---(2)---3--(2)--5 | | (3) (2) | | 2--(-10)--4 The minimum path is 1 - 2 - 4 - 3 - 5, with cost -3. However, Dijkstra will set d[3] = 2, d[2]...

java,algorithm,graph,nodes,dijkstra

Run BFS from the source (let it be s) on the graph to find the length of the shortest path from s to the target t, let it be d. Also mark d(s,v) - the distance from s to any node v. Create a subgraph G'=(V',E') of G such...

You address two questions: Dynamic Algorithms mean breaking a procedure down into simpler tasks. Several dynamic algorithms iclude the idea of recursion but are not limited too.. Considering Dijkstra's algorithm the clasic solution is given by a for loop and is not a dynamic algorithm solution. However, From a dynamic...

You should update your code according to changes in property maps in 1.55. Use make_iterator_property_map instead of raw pointers: dijkstra_shortest_paths(g,s, boost::predecessor_map(boost::make_iterator_property_map(p.begin(), get(boost::vertex_index, g))). distance_map(boost::make_iterator_property_map(d.begin(), get(boost::vertex_index, g))). weight_map(get(&EdgeDef::dist,g))); See changes in 1.55 and this bug https://svn.boost.org/trac/boost/ticket/7877...

algorithm,dijkstra,shortest-path

Actually for an unweighted, undirected graph, you don't need to use Dijkstra, a simple BFS shall serve the purpose. Following method checks whether e is a part of atleast one shortest path from s to t: Compute the shortest path from s to e and the shortest path from e...

After updating the distances, your vector won't be a heap anymore. Further more, calling sort_heap in itself would also drop the heap property, instead of fixing it. (See http://en.cppreference.com/w/cpp/algorithm/sort_heap) Call make_heap instead. Also note the memory leak: you never deallocate the memory allocated for the Vertex3 objects....

python,algorithm,dictionary,graph-algorithm,dijkstra

Dijkstra's algorithm solves the single-source shortest-path problem. Given a graph and a vertex in the graph, it finds the shortest path to every other vertex. If you want your implementation to run fast, you must use a priority queue. It's fine to use a dictionary to represent the graph initially,...

java,pointers,arraylist,dijkstra

Here is an example trying to mimic what you explained. It works for me hence, the error should be somewhere else i guess: public class Example { public static void main(String[] args) { List<Node> bestWay = new ArrayList<Node>(); Node chosen = new Node("Place1"); String from = chosen .add("Place2") .add("Place3") .add("Place4")...

java,algorithm,dijkstra,vertex

Yes the vertices store information about the cost and the path that is constructed. The problem is not that much that the path itself is constructed but the minDistance is the distance from a given start vertex. You can implement a method reset in the Vertex class void reset ()...

algorithm,dijkstra,shortest-path,traveling-salesman

You can reduce your graph to a TSP and then invoke a TSP algorithm on it: Use Floyd-Warshall algorithm to find the distance u,v for ALL pairs of vertices u and v. Create a new graph, containing only the "desired" vertices, and set the weight between two such vertices u...

python,algorithm,dictionary,graph-algorithm,dijkstra

You can still use a heap even if it requires a list. graph.keys() returns a list of keys in your dictionary. The heap can then be built using the keys and if you need to find vertexes, dictionary lookup can be used. vertexes = graph[heap.pop()]....

c++,boost,dijkstra,boost-graph,adjacency-list

Okay. You've come a long ways since Boost adjacency_list _swap errors when using boost Dijkstra; the sample is self-contained and can compile¹ I figured I could just connect some dots and hope this would be helpful. 1. Using VEdge For the simplest option, I'd use Bundled Properties, and define VEdge...

algorithm,max,dijkstra,shortest-path

This falls under the issue of the Longest Path Problem. In other words, there is no efficient way to find max path (in your case, max profits) in an unweighted graph structure. However, you mentioned that it was a weighted graph, so you might still be able to still do...

algorithm,graph-theory,dijkstra,np-complete,hamiltonian-cycle

No, this is not possible. Your simplified problem is still NP-hard. A reduction from travelling salesman: Given a graph (V, E), find the shortest path that visits each v in V exactly once. Take an arbitrary vertex v in V. Split v into two vertices v_source and v_sink. Use your...

java,python,algorithm,graph,dijkstra

There's a very simple algorithm to solve the recurrence described in David's answer: We can use depth-first search with memoization to ensure that at every time all the subproblems that we need to solve the result for the current node are already known. This implicitly results in the topological order...

algorithm,sorting,dijkstra,shortest-path

Think about making a star graph (a graph with a single central node and a bunch of "outer ring" nodes, where each outer ring node has one edge connecting it to the central node) with n outer ring nodes. Then, link up each node vi in the outer ring to...

It is because you first call function compute for A then call it for C. some field like this : public double minDistance = Double.POSITIVE_INFINITY; public Vertex previous; are already have a value, so you need to delete pathcomputation for A or clear this values, you can do it with...

algorithm,graph,graph-theory,graph-algorithm,dijkstra

I think your approaches are actually equivalent, provided that for approach #1, you record only the shortest distance to each node for each number of red edges used -- you don't need to record the entire path (just as you don't need to record it for ordinary Dijkstra on an...

algorithm,network-programming,computer-science,dijkstra

If there are two entries with the same lowest cost, you can choose either - it doesn't matter. For example, if your tentative list looks like this: 10 4 9 7 7 3 2 11 5 2 and you were finding the minimum cost by using a sorted list, it...

With Visual Studio you can tell the debugger to break when an exception is thrown: http://msdn.microsoft.com/en-us/library/d14azbfh.aspx Using this technique you should be able to find the root cause....

You can just check that an edge does not have -1 weight: for (i = 1; i < size; i++) { if (cost[start][i] != -1) { d = dist[start] + cost[start][i]; if (d < dist[i] && selected[i] == 0) { dist[i] = d; prev[i] = start; } } if (min...

algorithm,graph-algorithm,dijkstra,bellman-ford

Yes, it will give the same results. It will run slower, though, as it could also have been used for graphs with negative edges (subject to the absence of negative cycles). If you look at the proof of BF's correctness, there is no assumption there that some of the edges...

python,algorithm,dijkstra,libtcod

I made my own implementation of the A* algorithm for aesthetic walk path generation; which included bridges which were placed only when they could, according to A*, considering an added step count: https://github.com/lillian-lemmer/sshrpg/blob/master/plotbrush/mapgen.py#L622 As you can see, all you need to do is manipulate the A* algorithm is to increase...

You can safely ignore the largest of the two costs for algorithm purposes. Assume there is a shortest path the uses the largest cost between two vertices, you can change it to use the smallest cost and the path will cost less, and that contradicts the assumption....

c++,algorithm,dijkstra,shortest-path

Map the coordinates to integer vertices using a hashmap. Now you have a graph with nodes as single numbers. Apply dijkstra's algorithm. Time complexity : O(V) for converting to integer vertices. O(V^2) for running dijkstra's algorithm. Therefore O(V^2) total complexity. Pseudo code: int cntr = 0; for(Edge e : graph){...

Here you overwrite the field's value. When you assign a new value of Edge[], the old one gets deleted. Did you intend to add instead? B.adjacencies = new Edge[]{ new Edge(F, 5) }; D.adjacencies = new Edge[]{ new Edge(F, 3) }; B.adjacencies = new Edge[]{ new Edge(A, 6) }; D.adjacencies...

google-maps,graph,routes,neo4j,dijkstra

Without a lot of extra information, it's difficult to give you a great answer to this question, but let me hit some basics. This should be enough to get you going, but then you're going to need to do additional work to develop your solution. In general, your data structure...

algorithm,maps,dijkstra,shortest-path,backtracking

Actually the matrix isn't required. The graph can just aswell be generated on runtime. The image can be converted into a map of walls and open spots by simply converting it into a two-colored image, where one color represents walls. This would look like this for your requirements: define node:...

In this case you can implement the allShortestPaths, ordering the paths in an ascending order based on your distance property of the relationships and return only one, based on your last post it would be something like this : MATCH (from: Location {LocationName:"x"}), (to: Location {LocationName:"y"}) , paths = allShortestPaths((from)-[:CONNECTED_TO*]->(to))...

I will not write the code, but I can explain to you how to approach the problem, and also give a basic idea why it works. I will use terms source and sink for the two nodes you are searching the path between. First, why it works. As you noticed...

You need a set of previous vertices instead of a single vertex. When updating and you find an equal length path, append the vertex to the previous vertex list, clear and replace it on finding a shorter path. Then processing that to display depends on exactly what you are doing...

algorithm,graph,dijkstra,directed-graph

Remove the negative edge (u, v), run Dijkstra twice: once starting at s (D1) and once starting at v (D2) The shortest path between s and t is: min(D1[t], D1[u]+D2[t]+w(u, v))....

c++,vector,graph,dijkstra,shortest-path

looks like you have two types: heap_node, and a node class. I'm not sure which type is adj, but either way, you cannot make the vector type an instance. it has to be a type. So either make it typedef struct heap_node HEAP_NODE_STRUCT vector<HEAP_NODE_STRUCT> or c hange the heap_node struct...

No, there shouldn't be an infinite cycle. Visited and unvisited nodes in the graph are kept track of, and a visited node will never be visited again. In your example: Mark all nodes as unvisited, except for the starting node which is visited Starting with A, visit B, mark B...

If the cost of the edge between 1 and N is A. 1) if A<B, then the lowest cost will be A. 2) if A>B, then use BFS to find the fewest hops from 1 to N through only the edges with cost B. Assume that there are at...

You can't access them because they are initialized within a function. You need to declare them as global variables. ArrayList<Vertex> vertexObjects = new ArrayList<Vertex>(); ArrayList<Edge> edgeObjects = new ArrayList<Edge>(); ArrayList<Vertex> visitedObjects = new ArrayList<Vertex>(); ArrayList<Vertex> unvisitedObjects = new ArrayList<Vertex>(); ArrayList<Edge> tempEdge = new ArrayList<Edge>(); int numVertices = 0; String startVertex,...

c++,algorithm,data-structures,dijkstra,shortest-path

In minDistance(), if (includ[v] == false && dist[v] <= min) min = dist[v]; min_index = v; You missed { }. min_index = v; is executed no matter the condition is true or false....

algorithm,tree,dijkstra,shortest-path,bellman-ford

Dijkstra's algorithm requires the edge lengths to be nonnegative, while Bellman-Ford only requires the nonexistence of cycles of negative length.

algorithm,data-structures,graph,dijkstra,shortest-path

The flag is not needed. Just look at this section of pseudocode: if v is not yet scanned: alt = dist[u] + length(u, v) if alt < dist[v] dist[v] ← alt prev[v] ← u Q.decrease_priority(v,alt) end if end if If you check the different parts: alt seems to be a...

algorithm,graph,dijkstra,vertices

If by "distance" you mean "shortest distance", then the answer is "Yes". A very popular algorithm for all-pairs shortest paths is Floyd Warshall Algorithm. It is remarkably easy to implement: for k = 0 ; k != N ; k++ for i = 0 ; i != N ; i++...

You can use Bellman-Ford's algorithm, and instead to run until |V| - 1 in the outer loop, run until k. The outer loop iterator indicates the maximal length of the shortest path from the source to each target. From wikipedia (with the outer loop index modification) for i from 1...

algorithm,optimization,computer-science,dijkstra,shortest-path

If I understand you correctly, you want to find the tree of minimal weight in the graph that contains all the vertices of E and at least one vertex from S. The problem is called general Steiner tree, and it is NP-hard. So the best you can probably hope for...

algorithm,time-complexity,dynamic-programming,dijkstra

Dijkstra's Algorithm is not restricted to DAGs; it can be run on any graphs with no negative path weights, cyclic or otherwise. Topological sorting, that you most likely are referring to, fails the "arbitrary" clause of your Wiki quote.

You can just use networkx.shortest_path(G) with the weight='weight' keyword. e.g. In [1]: import networkx as nx In [2]: G = nx.Graph() In [3]: G.add_edge(1,2,weight=7) In [4]: G.add_edge(1,4,weight=3) In [5]: G.add_edge(2,3,weight=1) In [6]: G.add_edge(3,4,weight=100) In [7]: nx.adjacency_matrix(G).todense() Out[7]: matrix([[ 0, 7, 0, 3], [ 7, 0, 1, 0], [ 0, 1,...

python,algorithm,dictionary,dijkstra

Using a for loop will iterate over the keys of a dictionary, and by using the key, you can fetch the value that is associated to the key. If the value itself is a dictionary, you can use another loop. for fromNode in g: neighbors = g[fromNode] for toNode in...

algorithm,union,time-complexity,dijkstra

So the time complexity of the algorithm is equal to the time complexity of the lines (3-9)+O(E). Which is the time complexity of the union? No, it is not the complexity of the union, union can be done pretty efficiently if you are using hash table for example. Moreover,...

python,graph,networkx,dijkstra

The problem is that you have to write the word "weight" for assigning it to an edge. You are giving labels to the edges but no weights. The next code works printing 9 when you calculate the distance between nodes A and C. import networkx as nx G = nx.MultiDiGraph()...

The distance is known inside the shortestPath() function, just before it returns the path itself. At this point you can simply add the distance: return { path: path, distance: distances[finish] }; Then, on the caller side: var data = graph.shortestPath(startPoint, endPoint) var ShortestPath = data.path.concat([startPoint]).reverse(); var MinsTaken = data.distance; ...

In your reset function: public void reset() { this.minDistance = Double.POSITIVE_INFINITY; } I recommend you also reset previous public void reset() { this.minDistance = Double.POSITIVE_INFINITY; this.previous = null; } or you will get an infinite loop when tracing the path backwards....