Match the pairs search algorithm? - c#

I found an interesting pairs matching game at http://xepthu.uhm.vn. The rule is simple, you have to find and connect two identical pokemon but the path between them is not blocked and the direction can't not be changed 3 times. Let's see an example:
I've think alot about the algorithm to check if the path between any 2 selected pokemon is valid but because I'm a newbie so I can't find any solution. Can you suggest me one in C#?

This is basically a path finding problem from graph theory. The fields in the grid are the nodes, and all adjacent fields are connected by an edge.
Path finding is a well-known problem, and there are many algorithms that solve this. Since your graph is quite small, the best solution here is probably just a brute force algorithm. A popular path finding algorithm is Dijkstra's algorithm.
Brute force: Start at some pokemon and explore all possible ways to see if one leads to an identical pokemon. You can stop exploring a way if the way is blocked or has more than 2 turns.
You'll need some "pointer" pointing to a field in the grid. The pointer can move left, right, up or down, provided that the field in that direction is not blocked. Move the pointer to an adjacent field. Remember where you came from and how many turns you made. Repeat this until you've reached your destination. Backtrack if the number of turns reaches 3. Make sure you don't run in circles.

Take a look at planar graphs. You will have to introduce a second condition: no more than four nodes may be traversed (start node - first direction change - second direction change - end node).

Related

Closest pair of points from two sets, one from each

I have two sets of points, A and B, and I'm trying to find the closest pair of points where one point is taken from each set. That is, if you were to use the points two draw to lines, I want the two points that allow me to draw the shortest line segment between the two lines.
Looking around, almost everything seems to deal with finding the closest points in 1 set. Although I did find one solution recommending voronoi tesselation to begin with, which seems a bit like overkill, I'm just looking for something a bit nicer than O(n^2).
If it helps, the two sets I'm comparing form lines, although they are not necessarily straight and I'm writing this in C#.
Thanks.
It should be possible to adapt the classical D&C algorithm (as described in the Wikipedia link), by processing all points together and tagging them with an extra bit.
The merging step needs to be modified to accept candidate left-right pairs with a member from every set only. This way, the recursive function will return the closest A-B pair. The O(N.Log(N)) behavior should be preserved.
If the "lines" you mention have a known equation so that point/line distances (or even line/line intersections) can be evaluated quickly, there could be faster solutions.

Generating isochrone maps from road networks

I wonder if there's any described algorithm that can convert isochrones into approximate area to show a range of some feature (in my problem this feature is a road network).
Example. I have something like on the image beneath:
It's a simple network (where I can arrive from the start point in X minutes or going Y kilometers). I have information of all the nodes and links. Now I need to create an isochrone map that show an approximate range where I can arrive.
Problems:
Convex hull - sucks because of too general approximation,
I can create buffors on roads - so I will get some polygon that shows range, but I will also have the holes by roads that connect into circles.
What I need to obtain is something like this:
I've found some potentially useful information HERE, but there are only some ideas how it could be done. If anyone has any concept, please, help me to solve my problem.
Interesting problem, to get better answers you might want to define exactly what will this area that shows the range (isochrone map) be used for? For example is it illustrative? If you define what kind of approximation you want it could help you solve the problem.
Now here are some ideas.
1) Find all the cycles in the graph (see link), then eliminate edges that are shared between two cycles. Finally take the convex hull of the remaining cycles, this together with all the roads, so that the outliers that do not form cycles are included, will give a good approximation for an isochrome map.
2) A simpler solution is to define a thickness around each point of every road, this thickness should be inversely proportional to how long it takes to arrive at that point from the starting point. I.e. the longer it takes to arrive at the point the less thick. You can then scale the thickness of all points until all wholes are filled, and then you will have an approximate isochrome map. One possible way of implementing this is to run an algorithm that takes all possible routes simultaneously from the starting point, branching off at every new intersection, while tracking how long it took to arrive at each point. During its execution, at every instant of time all previously discovered route should be thickened. At the end you can scale this thickness so as to fill all wholes.
Hopefully this will be of some help. Good luck.
I have solved the problem (it's not so fast and robust, but has to be enough for now).
I generated my possible routes using A* (A-Star) algorithm.
I used #Artur Gower's idea from point one to eliminate cycles and simplify my geometry.
Later I decided to generate 2 types of gemetries (1st - like on the image, 2nd - simple buffers):
1st one:
3. Then I have removed the rest of unnecessary points using Douglas-Peucker algorithm (very fast!).
4. In the end I used Concave Hull algorithm (aka Alpha-Shapes or Non-Convex Hull).
2nd one:
3. Apply a buffer to the existing geometry and take the exterior ring (JTS library made that really easier:)).

A* search for Rush Hour game?

For an assignment for school I have to make a solver for a Rush Hour game.. if you aren't familiar with Rush Hour.. check this link: http://www.puzzles.com/products/rushhour.htm
For this solver I have to use the A* search algorithm, I looked on the internet a bit, and I think I quite understood how the algorithm works.. only I don't really have an idea how to implement it in the solver.. nor how I should build up the grid for the cars.. Can someone please give me some tips/help for this?
Not a complete solution..
To represent the grid of cars, I'd just use a rectangular array of cells where each cell is marked with an integer -- 0 indicates "empty", and each car has a particular number, so the different cars in the grid will manifest themselves as consecutive cells with the same number.
At this point, you should be able to write a function to return all the possible "moves" from a given grid, where a "move" is a transition from one grid state to another grid state -- you probably don't need to encode a better representation of a move than that.
To implement A*, you'll need a naive heuristic for figuring out how good a move looks, so you know which moves to try first. I would suggest initially that any move which either moves the target car closer to the goal or makes space nearer the front of the target car might be a better candidate move. Like Will A said in the comments, unless you're solving a 1000x1000 Rush Hour board, this probably isn't a big deal.
That's all the tricky parts I can think of.
As mquander or Will have already pointed out, the A* algorithm might be a bit an overfit for your problem.
I just give you now some hints what other algorithm you can use to solve the problem.
I don't want to explain how those algorithms work since you can find many good description in the internet. However, if you have a question, don't hesitate to ask me.
You can use some algorithms which belong to the kind of "uninformed search". There you have for example breadth first search, deep-first search, uniform cost search, depth-limited search or iterative deepening search. If you use breadth-first search or uniform cost search then you might have to deal with available memory space problem since those algorithms have an exponential space complexity (and you have to keep the whole search space in memory). Therefore, using a deep-first search (space complexity O(b*m)) is more memory friendly since the left part of the tree which you visit firstly can be omitted if it does not contain the solution. Depth-limited search and iterative deepening search are almost the same, whereas in the iterative deepening search you increase the search level of your tree iteratively.
If you compare time complexity (b=branching factor of the tree, m=maximum depth of the tree, l=depth level limit, d=depth of the solution):
breadth-first: b^(d+1)
uniform cost: b^?
depth-fist:b^m
depth-limited: b^l if (l>d)
iterative deepening: b^d
So as you can see iterative deepening or breadth-first search perform quite well. The problem of the depth-limited search is if your solution is located deeper than you search level, then you will not find a solution.
Then you have the so called "informed search" such as best-first search, greedy search, a*, hill climbing or simulated annealing. In short, for the best-first search, you use an evaluation function for each node as an estimate of “desirability". The goal of the greedy search is to expand the node which brings you closer to goal. Hill climbing and simulated annealing are very similar. Stuart Russell explains hill climbing as following (which I like a lot...): the hill climbing algorithm is like climbing Everest in thick fog with amnesia". It is simply a loop that continually moves in the direction of increasing value. So you just "walk" to the direction which increases your evaluation function.
I would use one of the uniformed search algorithms since they are very easy to implement (you just need to programme tree and traverse it correctly). Informed search performs usually better if you have a good evaluation function...
Hope that helps you...

Best logic for creating a (true) random labyrinth

I've been trying to make a little simple game just to test my logics, and it's a simple labyrinth, it's ugly, and so far sucky.
The engine works pretty well, given that the labyrinth already exists (a matrix), it could be even enjoyable, but I have no intention on drawing a bunch of maps, which might be setting values on 400 (20x20) fields of a matrix. not funny.
Then I've created a function to randomize it, setting floor/wall for each field, and (I expected that) not every map is winnable. then I've made another function which checks if the maps is playable (receives two points, and checks if there's a valid path between them, then I just pass the start and the end. Pretty nifty) and it worked.
If you haven't noticed, this is a VERY stupid way of creating my random labyrinth for the following reasons:
1 - It might come out really easy (giant isles of floor, or a bunch of walls together, making only one, extremely visible path, creating a stupit (though valid) labyrinth
2 - It is potentially the fastest way of creating a perfect random labyrinth EVER, but at the same time it's potentially the slowest too, taking as long as... infinite. This difference is noticed more when I set the grid for 30x30 or more (when something is not overflown)
3 - It's dumb and an offence to logic itself.
In my deffense, I didn't plan making it this way from the beginning, as described, one thing led to another.
So I've started thinking about ways to do a beautiful (full of paths, tricky and winnable) labyrinth, then I've thought about making tiny small (let's say) 5x5 blocks with predesigned entrances and mount them together in a way that it fits, but it would go against my true random desire, as well as my unwillingness to draw it by hand.
Then I've thought about a function to create a random path, run it once to the end, and run it several times to somewhere close to the end, and some crossings and stuff, some creating dead ends, which seemed better to me, but I just couldn't imagine it creating a decent labyrinth.
You can check what I've done so far in this link.
Note: I have no intentions in harming anyone's pc with anything.
First one to open it, please comment here saying that it's safe. - Done (thank you, Jonno_FTW)
If you still don't trust it, use a Virtual Machine.
OBS: I know this is not the best way of developing anything. I should get a decent game engine, bla bla bla, it was some kind of challenge for myself.
I've done maze generation. You don't want to place stuff randomly and validate. Instead, you generate it out from a starting point.
Pick a starting point, move in a random direction. Have a random probability of picking a new direction. Never move into an occupied square, if you bump into one the current trail ends. If the current trail ends pick a square you have already visited and pick a new direction and do a random walk like you did for the first one. Repeat until the maze is as full as you want it to be.
The probability of the direction change should be an input parameter as it makes quite a difference. Note that if you are doing a 3D maze the odds of a vertical turn should be a lot lower than the odds of a horizontal move.
Here's an expansive website dedicated to labyrinths:
http://www.astrolog.org/labyrnth/algrithm.htm
Explains what types of labyrinths there are, goes over the generation algorithms and the solution algorithms, has a lot of cool pictures.
Have a look at the source code in my Roguelike game, Tyrant:
Code for Dungeon.java
There are a lot of diferent map generation techniques used to produce the different level types. But the most basic pattern is to iterate the following:
Start with a blank map
Create a single random room / open space in the map
Randomly select a tile at the edge of the currently open area
Attempt to "grow" a corridor or room randomly out from that space (if it doesn't fit, do nothing)
Loop back to step 3 as many times as you need to create a decent maze
Finally, do a pass over the whole map and convert and remaining blank space to walls
Here's a screenshot of the type of thing you get (Look at the mini-map from the maze structure):
Tyrant screenshot http://www.freeimagehosting.net/uploads/af45502c9c.png
Your question makes me think of the XScreensaver Maze program. Look at its screenshots to see if that's the desired effect.
It looks like it took its maze generation algorithm from Wikipedia.
Wikipedia has a great article on Maze generation algorithms
How you create a random labyrinth will depend on what you want it to look like. If you're creating something that's designed to have a lot of dead ends, then you can just "randomly" trace a path from the start point to the end point, and then randomly fill in the empty spaces, essentially carving the path out of a solid block of material. E.g. imagine you had a stone tablet. First step would be to carve the "solution" path. Then you'd go in and make all of the dead ends.
If you want something that's more "play" than "puzzle", then creating a bunch of tile pieces that fit together in different ways is probably the way to go. That's how the Diablo games did it as far as I can tell; a number of predesigned "sets" and rules about how they fit together. You'd mark the four sides of the block with things like "three open spaces followed by two closed," and then if another piece also has a matching description, they can be put together.
After that, all you have to do is figure out how you can consistently render "random" behavior.
There's actually a trick that Al Lowe used for one of his Leisure Suit Larry games (LSL 3, I believe) that might be helpful.
Basically, he made a bamboo forest 'maze' that the player had to navigate. Rather than creating a separate 'square' of maze for each screen, however, he simply 'flipped' the one screen he had already created and made dead ends by blocking various entrances with a single 'bamboo wall' graphic.
Perhaps you could do the same: have the generator carve a valid maze, and then tell it to place dead-end blocks along some of the paths. That would ensure that there's always at least one valid, open path to the 'finish line', as well as preventing players from just strolling through a super-easy layout.
It'll also make a 30x30 maze more workable, since the computer won't have to test every square of a 900-square grid for validity.

Longest Path between two vertices

I have a directed graph with weighted edges (weights are all positive).
Now, I'm looking for an efficient algorithm or code (specifically, C#) to find the longest path between two given vertices.
This is exactly equivalent to a shortest-path algorithm with all negative weights. To do that, you need to verify that there are no negative-weight cycles (which in your original case is probably equivalent to verifying no positive-weight cycles). Best bet is to take the additive inverse of the weights and run Bellman-Ford, then take the additive inverse of the result.
David Berger's answer is correct, unless you mean a simple path, where each vertex can occur at most once, in which case Bellman-Ford will not give the longest path. Since you say the weights are positive, it's not possible for a longest path to exist when the graph has a cycle (reachable from the source), unless you mean simple path. The longest simple path problem is NP-complete. See Wikipedia.
So, let's assume you mean a directed acyclic graph (DAG). In linear time, you can compute the longest path to each vertex v from the start vertex s, given that you know the longest path from s->*u for each u where u->v directly. This is easy - you can do a depth first search on your directed graph and compute the longest path for the vertices in reverse order of visiting them. You can also detect back edges whole you DFS using a 3-color marking (opened but not finished vertices are gray). See Wikipedia again for more information. Longest/shortest path finding on a DAG is sometimes called the Viterbi algorithm (even though it was given assuming a specific type of DAG).
I'd attempt the linear time dynamic programming solution first. If you do have cycles, then Bellman-Ford won't solve your problem anyway.
Please refer to the QuickGraph project as it provides .NET data structures implementing graphs, and also provides algorithms to operate on such data structures. I'm certain the algorithm you are looking for is implemented in the library.
Just in case it helps anyone, as I was looking for this for a while but couldn't find it, I used QuickGraph to solve a problem where I had to find the longest path that also complies with a certain rule. It is not very elegant as I did it a bit on brute force once I get the first result, but here it is.
https://github.com/ndsrf/random/blob/master/LongestSkiPath/LongestSkiPath/SkiingResolver.cs#L129-L161
To get the longest path you use an algorithm to find the shortest with lenghts = -1. And then to find subsequent longest paths I start removing edges from that longest path to see if I manage to get a "better" (based on the conditions of the problem) longest path.

Categories

Resources