Algorithm to find the shortest path in a matrix - c#

I tried to find an algorithm for the following problem, but I couldn't.
you have a matrix, 10X6 if it matters. (10 on x dimension 6 on y dimension).
the algorithm receives 2 point, the opening point and the target point.
the array is full of 0's and 1's and it should find the shortest path of 1's between them, and return the first point in this path (the next point in the way to the target).
But here's the catch:
each point can get the value only of the following points:
the point above it.
the point underneath it.
the point left to it.
the point right to it.
and to make things even harder: for every point, the value of other point may be different. for example:
the opening point is 0,0. the value of 0,1 is 1;
the opening point is 0,2. the value of 0,1 is 0.
I can calculate the value so it shouldn't matter for you...
So I thought the only way to solve it is with recursion because of the last condition but if you find another way, you're welcome.
The solution should be in LUA, C# or JAVA.

You can simply interpret your matrix as a graph. Every cell (i,j) corresponds to a node v(i,j) and two nodes are connected if an only if their corresponding cells are neighbors and both are set to 1.
The example matrix below has the four vertices v(0,0), v(0,1), v(1,0), and v(1,1), with edges {v(0,0),v(0,1)} and {v(0,1),v(1,1)} (the vertex v(1,0) is isolated).
1 1
0 1
As your graph is unweighted, you can simply use a breadth-first search (BFS) to find a shortest path. For pseudocode see: http://en.wikipedia.org/wiki/Breadth-first_search#Pseudocode
Your restriction that every entry in a matrix only knows its neighboring entries does not matter. When talking about graphs, this means that ever vertex knows its neighbors, which is exactly what you need in the BFS. Using a different graph when searching from different starting points does not make the problem harder either.
Just two comments to the poseudocode linked above:
It only checks whether there is a connection or not. If you actually want to have the shortest path, you need to change the following. When a new vertex u is added to the queue when seen from its neighbor t, you have to store a link at u pointing to t. When you finally found your target, following back the links gives you the shortest path.
Using a set to store which elements are already visited is inefficient. In your case, just use a boolean matrix of the same size as your input matrix to mark vertices visited.

Related

DataStructure algorithm for pathfinding in a pointcloud

I was unsure how to phrase the title. I am searching for good data structure / algorithm combination for the following problem:
I have about 20000 objects, each containing a set of values (integers) and a XYZ-Position (doubles). I want to find the object that fits the following conditions best:
1. Needs to be within a maximum distance from a given starting point
2. From a given starting point, it has to be reachable by requiring no "hopping" (i.e. "travelling" from one object with position XYZ to another object's position) with a distance greater than a given threshold
3. It has to have the maximum value (of a given position in the set of integers)
At first I thought about graph theory and pathfinding, but it does not seem to fit well. I have no distinct edges, so I would have to link every point with every other point and use the distance as a weight on the edge. This would result in a lot(!) of edges. Second problem is that pathfinding (if I am not mistaken) only takes one criteria (usually distance or costs) as search criteria. But I would need multiple criteria (distance, hop limit, int value).
Any thoughts and also any good libraries to solve this well?

Find in how many pieces where matrix sliced with recursion

I recently got an assigment , where I have 4 on 5 matrix with 0 and 1(zero's represent the cut parts of the matrix). I need to find a way to calculate in how many pieces matrix will be sliced and as I mentioned zero's represent the cut parts of the matrix so if from one border to another goes straight line of zero's it means the matrix was sliced on that line , as for example(in this pic I've marked where matrix would be split, a line of zero's slice it) :
So guys I know that you won't entirely solve this code for me and I don't need that, but what I need is to understand this :
Firstly how should I tell a compiler in wich direction(when he is going threw matrix ) he should be going, I have an idea with enumarations.
Secondly , what kind of condition sentence I should use that the compiler would recognise the line of zero's(if there is such) ?
Any help would be appreciated :)
You did not specify any requirements for the algorithm (such as time and space complexity), so I guess one answer, that correlates to some specific solutions, would be:
Go in all 4 directions
Don't condition on 0s to create the line, but try to look at the 1s and find to which piece they belong.
A general algorithm for this can be implemented as follows:
Create a helper matrix of the same size, a function to give you a new symbol (for example by increasing some number any time a symbol is asked for), and a data structure to store collisions
Go in all 4 directions starting from anywhere
Whenever you find a 0 in the original matrix, issue some new symbol to each of the new directions you are going from there
Whenever you find 1, try to store the values in the helper matrix. If there is already a value there, then:
Store in the collisions data structure that you found a collision between 2 symbols
Don't continue in any direction from this one.
This will traverse each cell at most 4 time, so time complexity is O(n), and when you are done you will have a data structure with all the collisions.
Now all you need to do is combine all entries in the other data structure to collect how many unique pieces you really have.

Calculate possible coordinates of Nodes

This might be a weird application.
The brief description of the problem is "How to get Absolute Coordination of nodes based on Relative Positions (distances) ?"
We have a number of Nodes (each with a unique ID) and a list specifying its Adjacent nodes and distance to each of them as Input.
The required output would be one possible way to lay out these nodes on a 2D Surface.
The resulting algorithm is going to be used in C#... So external .net libraries might help too.
It would be a great help if you could advise me an approach to do that.
Thank you in advance.
You must have coordinates of at least three known points at start.
Way I. If the known points are adjacent, the process is simple - you loop all your points, looking for such, which have in their lists three known points. Use two of them to count two possible positions, then use the third to choose right or left variant. Repeat the loops until you have no new points during a loop.
That simple algorithm has bad convergence - the errors are accumulating and far points could have bad coordinates. But as you have the coordinates integer, you can repair coords after each counting and have them good.
Way II. If the known points are not adjacent to each other, the process is more complicated.
Let's say, you have start known points A,B,C.
Take A and some its adjacent point D. Place it somewhere at the correct distance from A.
Find some point E adjacent to A and D. Choose any of two possible positions.
Starting from A, D, E, use the way I.
When you reach by distances the second start known point, let it be B, of course, it will be in bad place. Turn all the net you have built around A so, that B will get the correct coordinates. Continue the looping.
When you will reach the last of the start known points, C, it will be set correct or not. If not, mirror the whole net relatively AB axis - the C will be set correctly. (If not, you have bad data). Continue the way I looping till the end.
Both these two ways work if you have long lists for all points. If points have only few distances given, the task becomes much, much more complicated.

Efficiently find Delaunay Triangulation face, which a given point lies on

Given a Delaunay Triangulation of a point set, how should I index my triangulation to do quick point localization?
I'm currently looping over all the triangles. For each triangle, I'm checking if the given point is within triangle's bounding rectangle. If it is, I then check the triangle using geometry equations.
This is slow. Any ideas of how to make this search more efficient?
Mission accomplished, that's the way I ended up doing it:
1) Check if the point lies within triangle bounding rectangle.
2) Assign the point as the start of a horizontal line, ending at max width.
3) Check intersections from the triangles found in (1) with the line from (2).
4) If triangle intersect, check how many times the horizontal line intersect with the triangle.
5) If intersects 1 time, means point in triangle. Else, not in triangle.
Reference:
Fast generation of points inside triangulated objects obtained by cross-sectional contours
Ranging from quick and practical to theoretically robust, here are three approaches you could use:
Construct a regular grid where each cell contains a list of triangles that intersect it. Given a query point, in constant time determine the cell that contains it, then compare your query point against only those triangles that are in that cell's list.
Construct a quadtree where each leaf cell contains the triangles that intersect it. Localizing the query point to a quadtree leaf takes logtime, but this can be more efficient in both speed and memory overall.
Sweep a horizontal line down across all the triangles. Points in your point sets correspond to events. At each event, some triangles begin intersecting the sweepline, and other triangles stop intersecting the sweepline. You can use an immutable (aka persistent) sorted map data structure to efficiently represent this. map<double, sweepstate>, where the key is the y-intercept of the sweepline at an event and sweepstate is a sorted list of line segment pairs (corresponding to the left and right sides of triangles). Given a query point, you first use its y value to lookup a sweepstate, and then you do a single trapezoid containment test. (Two horizontal sweeplines and two line segments between them form a trapezoid.)
A common approach to solve this point location problem is the efficient Trapezoidal Decomposition. It reduces the query time to O(Log(N)) per point, after O(N.Log(N)) preprocessing time, using O(N) space.
It could also be that the distribution of your query points allows alternative/simpler approaches.
A solution is a hierarchical tree, I.e. dendogram or hierarchical cluster. For example use the euklidian distance:http://en.m.wikipedia.org/wiki/Hierarchical_clustering. Or you can use a metric tree.

Scent based pathfinding using C# in games

Was wondering if anyone has knowledge on implementing pathfinding, but using scent. The stronger the scent in the nodes surrounding, is the way the 'enemy' moves towards.
Thanks
Yes, I did my university final project on the subject.
One of the applications of this idea is for finding the shortest path.
The idea is that the 'scent', as you put it, will decay over time. But the shortest path between two points will have the strongest scent.
Have a look at this paper.
What did you want to know exactly??
Not quite clear what the question is in particular - but this just seems like another way of describing the Ant colony optimization problem:
In computer science and operations
research, the ant colony optimization
algorithm (ACO) is a probabilistic
technique for solving computational
problems which can be reduced to
finding good paths through graphs.
Well, think about it for a minute.
My idea would to divide the game field into sections of 32x32 (or whatever size your character is). Then run some checks every x seconds (so if they stay still the tiles around them will have more 'scent') to figure out how strong a scent is on any given tile. Some examples might be: 1) If you cross over the tile, add 3; 2) if you crossed over an adjacent tile, add 1.
Then add things like degradation over time, reduce every tile by 1 every x seconds until it hits zero.
The last thing you will need to worry about is using AI to track this path. I would recommend just putting the AI somewhere, and telling it to find a node with a scent, then goto an adjacent node with a higher/equal value scent. Also worry about crossing off paths taken. If the player goes up a path, then back down it another direction, make sure the AI does always just take the looped back path.
The last thing to look at with the AI would be to add a bit of error. Make the AI take the wrong path every once in a while. Or lose the trail a little more easily.
Those are the key points, I'm sure you can come up with some more, with some more brainstorming.
Every game update (or some other, less frequent time frame), increase the scent value of nodes near to where the target objects (red blobs) are.
Decrease all node scent values by some fall-off amount to zero.
In the yellow blob's think/move function get available nodes to move to. Move towards the node with the highest scent value.
Depending on the number of nodes the 'decrease all node scent values' could do with optomisation, e.g. maybe maintaining a a list of non-zero nodes to be decreased.
I see a big contradiction between scent model and pathfinding. For a hunter in the nature finding the path by scent means finding exactly the path used by the followed subject. And in games pathfinding means finding the fastest path between two points. It is not the same.
1. While modelling the scent you will count the scent concentration in the point as the SUM of the surrounding concentrations multiplied by different factors. And searching for the fastest path from the point means taking the MINIMUM of the times counted for surrounding points, multiplied by the different parametres.
2. Counting the scent you should use recursive model - scent goes in all directions, including backward. In the case of the pathfinding, if you have found the shortest paths for points surrounding the target, they won't change.
3 Level of scent can rise and fall. In pathfinding, while searching for minimum, the result can never rise.
So, the scent model is really much more complicated than your target. Of course, what I have said, is true only for the standard situation and you can have something very special...

Categories