Level solving and pathfinding - algorithm

I have played a little flash game recently called Just A Trim Please and really liked the whole concept.
The basic objective of the game is to mow the whole lawn by going over each square once. Your lawn mower starts on a tile and from there you can move in all directions (except where there are walls blocking you). If you run on the grass tiles more than once it will deteriorate and you will lose the level. You can only move left, right, up, or down.
However, as you finish the game, more tiles get added:
A tile you can only mow once (grass).
A tile you can run over twice before deteriorating it (taller grass).
A tiie you can go over as much as you want (concrete).
A tile you can't go over (a wall).
If you don't get what I mean, go play the game and you'll understand.
I managed to code a brute-force algorithm that can solve puzzles with only the first kind of tile (which is basically a variation of the Knight's Tour problem). However, this is not optimal and only works for puzzles with tiles that can only be ran on once. I'm completely lost as to how I'd deal with the extra tiles.
Given a starting point and a tile map, is there a way or an algorithm to find the path that will solve the level (if it can be solved)? I don't care about efficiency, this is just a question I had in mind. I'm curious as to how you'd have to go to solve it.
I'm not looking for code, just guidelines or if possible a plain text explanation of the procedure. If you do have pseudocode however, then please do share! :)
(Also, I'm not entirely sure if this has to do with path-finding, but that's my best guess at it.)

The problem is finite so, sure, there is an algorithm.
A non-deterministic algorithm can solve the problem easily by guessing the correct moves and then verifying that they work. This algorithm can be determinized by using for example backtracking search.
If you want to reduce the extra tiles (taller grass and concrete) to standard grass, you can go about it like this:
Every continuous block of concrete is first reduced into a single graph vertex, and then the vertex is removed, because the concrete block areas are actually just a way to move around to reach other tiles.
Every taller grass tile is replaced with two vertices that are connected to the original neighbors, but not to each other.
Example: G = grass, T = tall grass, C = concrete
G G T
G C T
C C G
Consider it as a graph:
Now transform the concrete blocks away. First shrink them to one (as they're all connected):
Then remove the vertex, connecting "through" it:
Then expand the tall grass tiles, connecting the copies to the same nodes as the originals.
Then replace T, T' with G. You have now a graph that is no longer rectangular grid but it only contains grass nodes.
The transformed problem can be solved if and only if the original one can be solved, and you can transform a solution of the transformed problem into a solution of the original one.

There is a DP approach for the travelling salesman.
Perhaps you could modify it (recalculating as more pieces are added).
For a long piece of grass, you could perhaps split it into two nodes since you must visit it twice. Then reconnect the two nodes to the nodes around it.

Related

Algorithm for finding shortest path between 2 objects

I have a floorplan with lots of d3.js polygon objects on it that represent booths. I am wondering what the best approach is to finding a path between the 2 objects that don't overlap other objects. The use case here is that we have booths and want to show the user how to walk to get from point a to b the most efficient. We can assume path must contain only 90 or 45 degree turns.
we took a shot at using Dijkstra but the scale of it seems to be getting away from us.
The example snapshot of our system:
Our constraints are that this needs to run in the browser. Would be nice if it worked well with d3.js.
Since the layout is a matrix (or nested matrices) this is not a Dijkstra problem, it is simpler than that. The technical name for the problem is a "Manhatten routing". Rather than give a code algorithm, I will show you an example of the optimum route (the blue line) in the following diagram. From this it should be obvious what the algorithm is:
Note that there is a subtle nuance here, and that is that you always want to maximize the number of jogs because even though the overall shape is a matrix, at each corner the person will actually walk diagonally (think of a person cutting diagonally across a four-way intersection). Therefore, simply going north, then west is wrong, because you would only get to cut one corner, but on the route shown you get to cut 5 corners.
This problem is known as finding shortest path between two points with polygonal obstacle, and studied a lot in literature. See here for one example. All algorithms for this is by converting problem to the graph theory problem then running Dijkstra. To doing this:
Each vertex in any polygon is vertex in your graph.
Start point and end points are also vertices in the graph.
Between two vertex there is an edge, if they are visible to each other, to achieve this we can use triangulation algorithms.
Weight of each edge is the distance between its two endpoints in Euclidean space.
Now we are ready to run any shortest path algorithm. The hard part is triangulation, I think triangle library fits for your requirements. Also easier way is searching the web by the keywords that I said in the first line to find implementation. I didn't link to any implementation because I see is better to say it in algorithmic manner to be useful to the future readers.

Maze solving algorithm. Complex mazes

I found several algorithms to solve mazes. Those which are simple enough are suitable only in cases when exit is in outer boundary (Wall-follower, pledge...).
Is there some more sophisticated algorithms for cases when shapes of boundaries are random, costs of zones inequal and exit may be somewhere inside the maze? (btw, all elements are quadratic)
Update: Also, we don't know apriori how maze looks like and are able to see only certain area.
If you mean "normal" 2-dimensinal mazes like those one can find on paper, you can solve them using image analysis. However, if you are somehow located in the (2D/3D) maze itself and should find a way out, you should probably deploy some Machine learning techniques. This works if you don't have any idea what you maze exactly looks like, a.k.a. you only "see" part of it.
Update: Apart from the shortest path finder algorithm family, I can also relate to the so-called Trémaux's algorithm designed to be able to be used by a human inside of the maze. It's similar to a simple recursive backtracker and will find a solution for all mazes.
Description:
As you walk down a passage, draw a line behind you to mark your path. When you hit a dead end turn around and go back the way you came. When you encounter a junction you haven't visited before, pick a new passage at random. If you're walking down a new passage and encounter a junction you have visited before, treat it like a dead end and go back the way you came so that you won't go around in circles or missing passages. If walking down a passage you have visited before (i.e. marked once) and you encounter a junction, take any new passage if one is available, otherwise take an "old" one. Every passage will be either empty (if not visited yet), marked once, or marked twice (if you were forced to backtrack). When you reach the solution, the paths which were marked exactly once will indicate the direct way back to the start. If the maze has no solution, you'll find yourself back at the start with all passages marked twice.
Shortest path algorithms are finding shortest path to the exit, no matter where the exit is.
If the cost is equal - BFS will do - otherwise, you need something like dijkstra's algorithm or A* algorithm [which is basically an informed dijkstra] to find the shortest path.
To use these algorithms, you need to model your maze as a graph: G=(V,E) where V = { all moveable squares in the maze } and E = {(u,v) | you can move from u to v in a sinlgle step }
If the squares have cost let it be cost(v) per each square, you will need a weighting function: w:E->R: define it as w(u,v) = cost(v)
The Pledge Algorithm is useful for the kind of mazes you are talking of. It consists of:
Picking a direction, if you know the general direction to goal good, but a random direction will do. Let say you pick North.
Go that direction until you hit an obstacle.
Follow the obstacle, keeping track of how much you turn. For instance, going North you run into an East-West wall. You turn East (90d), and follow the wall as it turns South (180d), West (270d), and North again (360d). You do not stop following the wall until the amount you have turned becomes 0. So you keep following as it turns West (270d it turned in the opposite direction), South (180d), East (90d), and finally North (0d). Now you can stop following.
Do that any time you hit an obstacle. You will get to the Northern most part of the maze eventually. If you still havent found the goal, because you picked the wrong direction, try again with East or South or whatever direction is closest to the goal.

reflection paths between points in2d

Just wondering if there was a nice (already implemented/documented) algorithm to do the following
boo! http://img697.imageshack.us/img697/7444/sdfhbsf.jpg
Given any shape (without crossing edges) and two points inside that shape, compute all the paths between the two points such that all reflections are perfect reflections. The path lengths should be limited to a certain length otherwise there are infinite solutions. I'm not interested in just shooting out rays to try to guess how close I can get, I'm interested in algorithms that can do it perfectly. Search based, not guess/improvement based.
I think you can do better than computing fans. Call your points A and B. You want to find paths of reflections from A to B.
Start off by reflecting A in an edge, and call the reflection A1. Can you draw a line from A1 to B that only hits that edge? If yes, that means you have a path from A to B that reflects on the edge. Do this for all the edges and you'll get all the single reflection paths that exist. It should be easy to construct these paths using the properties of reflections. Along the way, you need to check that the paths are legal, i.e. they do not cross other edges.
You can continue to find paths consisting of two reflections by reflecting all the first generation reflections of A in all the edges, and checking to see whether a line can be drawn from those points through the reflecting edge to B. Keep on doing this search until the distance of the reflected points from B exceeds a threshold.
I hope this makes sense. It should be easier than chasing fans and dealing with their breakups, even though you're still going to have to do some work.
By the way, this is a corner of a well studied field of billiards on tables of various geometries. Of course, a billiard ball bounces off the side of a table the same way light bounces off a mirror, so this is just another way of thinking of reflections. You can delve into this with search terms like polygonal billiards unfolding illumination, although the mathematicians tend to dwell on finding cases where there are no pool shots between two points on a polygonal table, as opposed to directly solving the problem you've posed.
Think not in terms of rays but fans. A fan would be all the rays emanating from one point and hitting a wall. You can then check if the fan contains the second point and if it does you can determine which ray hits it. Once a fan hits a wall, you can compute the reflected fan by transposing it's origin onto the outside of the wall - by doing this all fans are basically triangle shaped. There are some complications when a fan partially hits a wall and has to be broken into pieces to continue. Anyway, this tree of reflected fans can be traversed breadth first or depth first since you're limiting the total distance.
You may also want to look into radiosity methods, which is probably similar to what I've just described, but is usually done in 3d.
I do not know of any existing solutions for such a problem. Good luck to you if you find one, but incase you don't the first step to a complete but exponential (with regard to the line count) would be to break it into two parts:
Given an ordered subset of walls A,B,C and points P1, P2, calculate if a route is possible (either no solutions or a single unique solution).
Then generate permutations of your walls until you exceed whatever limit you had in mind.
The first part can be solved by a simple set of equations to find the necessary angles for each ray bounce. Then checking each line against existing lines for collisions would tell you if the path is possible.
The parameters to the system of equations would be
angle_1 = normal of line A with P1
angle_2 = normal of line B with intersection of line A
angle_3 = normal of line C with ...
angle_n = normal of line N-1 with P2
Each parameter is bounded by the constraints to hit the next line, which may not be linear (I have not checked). If they are not then you would probably have to pick suitable numerical non-linear solvers.
In response to brainjam
You still need wedges....
alt text http://img72.imageshack.us/img72/6959/ssdgk.jpg
In this situation, how would you know not to do the second reflection? How do you know what walls make sense to reflect over?

Solving a picture jumble!

What algorithm would you make a computer use, if you want to solve a picture jumble?
You can always argue in terms of efficiency of the algorithm, but here I am really looking at what approaches to follow.
Thanks
What you need to do is to define an indexing vocabulary for each face of a jigsaw puzzle, such that the index of a right-facing edge can can tell you what the index of a corresponding left-facing edge is (e.g, a simple vocabulary: "convex" and "concave", with "convex" on a face implying "concave" on a matching opposite face), and then classify each piece according to the indexing vocabulary. The finer the vocabulary, the more discrimantory the face-matching and the faster your algorthm will go, however you implement it. (For instance, you may have "flat edge, straight-edge-leans-left, straight-edge-leans-right, concave, convex, knob, knob-hole, ...). We assume that the indexing scheme abstracts the actual shape of the edge, and that there is a predicate "exactly-fits(piece1,edge1,piece2,edge2)" that is true only if the edges exactly match. We further assume that there is at most one exact match of a piece with a particular edge.
The goal is grow a set of regions, e.g., a set of connected pieces, until it is no longer possible to grow the regions. We first mark all pieces with unique region names, 1 per piece, and all edges as unmatched. Then we enumerate the piece edges in any order. For each enumerated piece P with edge E, use the indexing scheme to select potentially matching piece/edge pairs. Check the exactly-fits predicate; at most one piece Q, with edge F, exactly-matches. Combine the regions for P and Q together to make a large region. Repeat. I think this solves the puzzle.
Solving a jigsaw puzzle can basically be reduced to matching like edges to like edges. In a true jigsaw puzzle only one pair of pieces can properly be interlocked along a particular edge, and each piece will have corners so that you know where a particular side starts and ends.
Thus, just find the endpoints of each edge and select a few control points. Then iterate through all pieces with unbound edges until you find the right one. When there are no more unbound edges, you have solved the puzzle.
To elaborate on Ira Baxter's answer, another way of conceptualizing the problem is to think about the jigsaw puzzle as a graph, where each piece is a node and each iterface with another piece is an edge.
For example if you were designing a puzzle game, storing the "answer" this way would make "check if this fits" code a lot faster, since it could be reduced to some sort of hash-lookup.
.1 Find 2x2-grams such that all four edges will fit. Then, evaluate how well the image content matches with each other.
P1 <--> P2
^ ^
| |
v v
P3 <--> P4
.2 Tag orientations (manually or heuristically), but only use them as heuristics scores (for ranking), not as definitive search criteria.
.3 Shape Context

Which is the best way to solve this kind of game?

This evening I tried to solve a wood puzzle so I wondered which is the best way to find a solution to this kind of problem programmaticaly.
The aim is to combine a set of solids (like tetris pieces in three dimensions) together to form a shape in a feasable way that takes into account the fact that pieces can be attached or slided into the structure only if they fit the kind of movement (ignore rotations, only 90° turns).
Check this picture out to understand what I mean.
In my latest CS class we made a generic puzzle solver that worked by having states represented as objects in C++. Each object had a method to compare the state it represented to another state. This was used for memoization, to determine if states had already been seen. Each state also had a method to generate states directly reachable from that state (i.e. rotating a block, placing a block, shifting a block). The solver worked by maintaining a queue of states, popping a state off the front of the queue, checking to see if it was the desired state (i.e. puzzle solved). If not, the memoization (we used a hashed set) was checked to see if the state had already been seen. If not, the states reachable from the current state were generated and appended to the rear of the queue. An empty queue signaled an unsolvable puzzle.
Conceptualizing something like that for 3D would be hard, but that is the basic approach to computerized puzzle solving.
Seems like an easier subset of a three-dimensional polyomino packing problem. There are various scholarly papers on that subject.
As it is a more or less small problem because for a computer there is a small number of combinations possible I would try a simple search algorithm.
I mean an algorithm that checks every possible configuration and goes on from the result of this configuration until it ends up in a end configuration, in your case the cube.
The problem seams to be writing a program that is able to do all the state checks and transformations from one state to another. Because you have to see if the configuration is physically possible.
If the puzzle you want to handle is that one in the photo you have linked, then it's probably feasible to just search through a tree of possible solutions until you find your way to the bottom.
If each puzzle piece is a number of cubes attached at their faces, and I am to solve the puzzle by fitting each piece into a larger cube, 4 times on each edge as the composing cubes, then I'd proceed as follows.
Declare an arbitrary cube of each piece as its origin. Observe that there are 24 possible rotations for each puzzle piece, one orientation for each possible face of the origin cube facing upwards, times 4 possible rotations about the vertical axis in that position.
Attempt to cull the search space by looking for possible orientations that produce the same final piece, if a given rotation, followed by a translation of the origin cube to any of the other cubes of the piece results in exactly the same occupied volume as a previously considered rotation, cull that rotation from future consideration.
Pull a piece out of the bag. If there are no pieces in the bag, then this is a solution. Loop through each cell of the solution volume, and each rotation of the pulled piece for each cell. If the piece is completely inside the search volume, and does not overlap with any other piece, recurse into this paragraph. Otherwise, proceed to the next rotation, or if there are no more rotations, proceed to the next cell, or if there are no more cells, return without a solution.
If the last paragraph returns without a solution, then the puzzle was unsolvable.

Resources