I am trying to learn graphs as well using Dijkstra’s path and am using this geeks for geeks tutorial. I think i understand how it works using weight to find the shortest path. However this may be dumb but i dont understand how to find the destination point by looking at the code. or how the 9 inputs are
Why are there 9 inputs cant it work with only three? And how does the program know where to end?
So, to address the first half of your question, there isn't a predetermined "destination node" with Dijsktra's algorithm, moreso just a final result.
In this example from the GeeksforGeeks code,
void dijkstra(int graph[V][V], int src)
We can see that the algorithm wants an array of all of the nodes, and which node you'll be starting from. Each node in this array has 9 inputs which correspond to that node's given distance from any other node, where a value of 0 represents no connection. For example, the "0" node has values:
{0, 4, 0, 0, 0, 0, 0, 8, 0}
Which mean that node 0 is 4 units away from node 1, 8 units away from node 7, and either has no connection to, or IS one of the other 7 nodes. If you only have 3 nodes, then you'd use 3 inputs to represent the possible distances between all 3.
When the program has exhausted all possible nodes and paths, the algorithm will stop. This algorithm looks for a minimum spanning tree, not a path from point A to point B.
The program in that example ends when all nodes have been visited, it does not choose a specific destination. It calculates the minimum distance (and path) from node 0 to every node in the graph.
There are 9 nodes in the example, but ofcourse you can also use 3 nodes, or 1000 nodes..
Related
Please bear with me I am very new to data structures.
I am getting confused how a priroity queue is used to solve min distance. For example if I have a matrix and want to find the min distance from the source to the destination, I know that I would perform Dijkstra algorithm in which with a queue I can easily find the distance between source and all elements in the matrix.
However, I am confused how a heap + priority queue is used here. For example say that I start at (1,1) on a grid and want to find the min distance to (3,3) I know how to implement the algorithm in the sense of finding the neighbours and checking the distances and marking as visited. But I have read about priority queues and min heaps and want to implement that.
Right now, my only understanding is a priority queue has a key to position elements. My issue is when I insert the first neighbours (1,0),(0,0),(2,1),(1,2) they are inserted in the pq based on a key (which would be distance in this case). So then the next search would be the element in the matrix with the shortest distance. But with the pq, how can a heap be used here with more then 2 neighbours? For example the children of (1,1) are the 4 neighbours stated above. This would go against the 2*i and 2*i + 1 and i/2
In conclusion, I don't understand how a min heap + priority queue works with finding the min of something like distance.
0 1 2 3
_ _ _ _
0 - |2|1|3|2|
1 - |1|3|5|1|
2 - |5|2|1|4|
3 - |2|4|2|1|
You need to use the priority queue to get the minimum weights in every move so the MinPQ will be fit for this.
MinPQ uses internally technique of heap to put the elements in the right position operations such as sink() swim()
So the MinPQ is the data structure that uses heap technique internally
If I'm interpreting your question correctly, you're getting stuck at this point:
But with the pq, how can a heap be used here with more then 2 neighbours? For example the children of (1,1) are the 4 neighbours stated above. This would go against the 2*i and 2*i + 1 and i/2
It sounds like what's tripping you up is that there are two separate concepts here that you may be combining together. First, there's the notion of "two places in a grid might be next to one another." In that world, you have (up to) four neighbors for each location. Next, there's the shape of the binary heap, in which each node has two children whose locations are given by certain arithmetic computations on array indices. Those are completely independent of one another - the binary heap has no idea that the items its storing come from a grid, and the grid has no idea that there's an array where each node has two children stored at particular positions.
For example, suppose you want to store locations (0, 0), (2, 0), (-2, 0) and (0, 2) in a binary heap, and that the weights of those locations are 1, 2, 3, and 4, respectively. Then the shape of the binary heap might look like this:
(0, 0)
Weight 1
/ \
(2, 0) (0, 2)
Weight 2 Weight 4
/
(0, -2)
Weight 3
This tree still gives each node two children; those children just don't necessarily map back to the relative positions of nodes in the grid.
More generally, treat the priority queue as a black box. Imagine that it's just a magic device that says "you can give me some new thing to store" and "I can give you the cheapest thing you've given be so far" and that's it. The fact that, internally, it coincidentally happens to be implemented as a binary heap is essentially irrelevant.
Hope this helps!
This is for a homework problem -
I need to find the median of a Binary Search Tree in O(h) time - meaning, I cant go through the whole tree to find it. I need to find the median by going through the left or right side of the tree, in a recursion solution.
I've placed an index into each node of the BST, using inorder traversal.
So if a BST has 99 nodes, the smallest node has an index of 1, the next smallest has index of 2 etc etc...while the largest node has index of 99. THis indexing is also required of the assignment.
So whichever side is heavier, has the median.
So here's what I was thinking:
if the left side has more nodes median is on the left. if right side has more nodes, median is on the right. if the left and right sides have equal num of nodes, median is the main root of the whole tree.
But I can't think of how the nodes' indexes would play a role in any of this. I was thinking of using the difference of 2 nodes' indexes to see if 1 side is heavier, but this would require me to go through the whole tree I think, so this would be O(n).
Please set me on a clearer path or a hint or 2.
I was given a graph, including a start vertex, other vertices, and edges represent the costs going from one vertex to another. I need to find the set of destination vertices that I can travel to from the start vertex. The budget is a certain amount of dollars and the travel total cost should be within the budget. How can i implement the Dijkstra's algorithm to this problem? I think we usually use Dijkstra to find the shortest path between two fixed vertices before. But I am not sure how to implement Dijkstra on this budget problem. If someone can give some ideas, that really helps!
To my undersatanding, Dijkstra's algorithm solves the single-source shortest path problem. This means that the resulting data structure is a tree rooted at the starting node. Typically, an implementation would store the minimum cost to reach each node from the starting node. In total, the set of vertices that can be reached within the budget are the ones to which the cost of the shortest path does not exceed the budget. The algorithm itself does not need to be modified; in an additional step, the nodes which can be reached within budged has to be returned as the output.
If you use Dijkstra algorithm, you may end up with the below scenarios:
Assuming budget of 50 and the graph of 4 nodes (start, node 1, node 2, node 3)
Start Node -> node 1 (15) -> node 2 (10): so total cost is 25
Start Node -> node 3 (15): total cost is 15
So now what is your expected result? You should go to node 1 then node 2 and ignore node 3 (since you cannot return back to start then go to node 3, the return will cost 30 too). Or you should go to node 1, back to start, then go to node 3 (total cost of 45, the largest cost you can utilise)
What you need is not the shortest path covering all destinations which is Floyd-Warshall algorithm https://en.wikipedia.org/wiki/Floyd–Warshall_algorithm
So how do I tackle this problem? I need to a program that reads a positive integer n from standard input and writes to standard output a representation of all distinct rooted, ordered, labeled trees on the set {1,2,3....n} of vertices.
For the output, I need to use the following linear textual representation L(t) of a tree t:
If t is empty then L(t) = ().
If t has root n and children, in sibling order, C = (c1; c2; : : : ; ck), then
L(t) = (n, (L(c1), L(c2), : : :, L(ck)))
where, L(ci) denotes the linear textual representation of the subtree rooted at
child ci. There is a single space after each comma in the representation.
The output should contain the representation of one tree on each line and should be
sorted by lexicographic order on the linear representations viewed as strings. The
output should contain nothing else (such as spurious newline characters, prompts, or
informative messages). Sample inputs and outputs for n = 1; 2; appear below.
enter code here
Input: 1
Output:
(1, ())
Input: 2
Output:
(1, ((2, ())))
(2, ((1, ())))
enter code here
Any help will be largely appreciated. I just need to be steered to a direction. Right now, I'm completely stumped :(
You can generate trees recursively. Start with a root. The root can have 0, 1, 2 ... (m - 1) children, where m is the number of vertices you have left to place. Start by placing (m - 1) vertices under the root, and then go down all the way to 0. You'll "place" these vertices recursively, so placing a vertex as child under the root means calling the same method again, but the maximum number of children will be a bit less this time.
You'll get two stopping criteria for the recursion:
You've placed all N vertices. You need to output the current tree then with your yet-to-define L(t) function, then backtrack to try different trees.
The algorithm gave all leaf vertices a degree of 0 and you haven't placed n vertices yet. Don't output this tree since it is invalid, but backtrack.
The algorithm is finished after it tries to give the root node 0 children.
As for the output L(t) function, it seems to suffice to do a depth-first tree traversal. Recursive is easiest to program (as this seems to be a practical assignment of some kind, that's probably what they want you to do). If you need speed, look for a non-recursive depth-first tree traversal algorithm on Wikipedia.
I have built a 8 puzzle solver using Breadth First Search. I would now want to modify the code to use heuristics. I would be grateful if someone could answer the following two questions:
Solvability
How do we decide whether an 8 puzzle is solvable ? (given a starting state and a goal state )
This is what Wikipedia says:
The invariant is the parity of the permutation of all 16 squares plus
the parity of the taxicab distance (number of rows plus number of
columns) of the empty square from the lower right corner.
Unfortunately, I couldn't understand what that meant. It was a bit complicated to understand. Can someone explain it in a simpler language?
Shortest Solution
Given a heuristic, is it guaranteed to give the shortest solution using the A* algorithm? To be more specific, will the first node in the open list always have a depth ( or the number of movements made so fat ) which is the minimum of the depths of all the nodes present in the open list?
Should the heuristic satisfy some condition for the above statement to be true?
Edit : How is it that an admissible heuristic will always provide the optimal solution? And how do we test whether a heuristic is admissible?
I would be using the heuristics listed here
Manhattan Distance
Linear Conflict
Pattern Database
Misplaced Tiles
Nilsson's Sequence Score
N-MaxSwap X-Y
Tiles out of row and column
For clarification from Eyal Schneider :
I'll refer only to the solvability issue. Some background in permutations is needed.
A permutation is a reordering of an ordered set. For example, 2134 is a reordering of the list 1234, where 1 and 2 swap places. A permutation has a parity property; it refers to the parity of the number of inversions. For example, in the following permutation you can see that exactly 3 inversions exist (23,24,34):
1234
1432
That means that the permutation has an odd parity. The following permutation has an even parity (12, 34):
1234
2143
Naturally, the identity permutation (which keeps the items order) has an even parity.
Any state in the 15 puzzle (or 8 puzzle) can be regarded as a permutation of the final state, if we look at it as a concatenation of the rows, starting from the first row. Note that every legal move changes the parity of the permutation (because we swap two elements, and the number of inversions involving items in between them must be even). Therefore, if you know that the empty square has to travel an even number of steps to reach its final state, then the permutation must also be even. Otherwise, you'll end with an odd permutation of the final state, which is necessarily different from it. Same with odd number of steps for the empty square.
According to the Wikipedia link you provided, the criteria above is sufficient and necessary for a given puzzle to be solvable.
The A* algorithm is guaranteed to find the (one if there are more than one equal short ones) shortest solution, if your heuristic always underestimates the real costs (In your case the real number of needed moves to the solution).
But on the fly I cannot come up with a good heuristic for your problem. That needs some thinking to find such a heuristic.
The real art using A* is to find a heuristic that always underestimates the real costs but as little as possible to speed up the search.
First ideas for such a heuristic:
A quite pad but valid heuristic that popped up in my mind is the manhatten distance of the empty filed to its final destination.
The sum of the manhatten distance of each field to its final destination divided by the maximal number of fields that can change position within one move. (I think this is quite a good heuristic)
For anyone coming along, I will attempt to explain how the OP got the value pairs as well as how he determines the highlighted ones i.e. inversions as it took me several hours to figure it out. First the pairs.
First take the goal state and imagine it as a 1D array(A for example)
[1,2,3,8,0,4,7,5]. Each value in that array has it's own column in the table(going all the way down, which is the first value of the pair.)
Then move over 1 value to the right in the array(i + 1) and go all the way down again, second pair value. for example(State A): the first column, second value will start [2,3,8,0,4,7,5] going down. the second column, will start [3,8,0,4,7,5] etc..
okay now for the inversions. for each of the 2 pair values, find their INDEX location in the start state. if the left INDEX > right INDEX then it's an inversion(highlighted). first four pairs of state A are: (1,2),(1,3),(1,8),(1,0)
1 is at Index 3
2 is at Index 0
3 > 0 so inversion.
1 is 3
3 is 2
3 > 2 so inversion
1 is 3
8 is 1
3 > 2 so inversion
1 is 3
0 is 7
3 < 7 so No inversion
Do this for each pairs and tally up the total inversions.
If both even or both odd (Manhattan distance of blank spot And total inversions)
then it's solvable. Hope this helps!