an algorithm that could find a random cycle in a graph - algorithm

I am looking for an algorithm that could find a random cycle in a graph from a node while that cycle is traversing around another nodes (area). For example, from the green star on the left of the image, finds a random cycle that goes around the red-star nodes.

Given that you are looking for a path that is "random", but still fairly close to minimal perimeter around the "red star", you could try this:
First, we need to choose the direction we are going. Let us decide on clockwise, and we start at point S.
Second, calculate the shortest path around the red star, including the point S. I am not going into details here (e.g. what if it is concave) since this is another question. Also, notice that deciding on S is already taking away from the randomness of the algorithm.
While choosing the path, keep 3 parameters (forward, left, right) that present the weight in the random choice of the next move. The difference in the outcome will be largely determined by the handling of theses parameters. You could always keep the weight equal, and then you might never get back to the start point, and even if you do, you don't know that the red star is inside.
To fix this, check the position with the minimal path calculated before.
If you are on it, then right = 0. Also, the directions going away from the minimal path could get less and less chances the further you are from it.
Hope this was helpful.

Related

hepl in identifying the given problem to a graph

A thief steals from you and gets a 20 meter head start. You could easily catch him on open ground, since you can run twice as fast and so catch up 5 meters for every 10 meters you travel. Once the theif reaches a time warp he is trying to get back to , you cant catch him and there are a bunch of rivers in the path: see Figure. There are N places (marked by black lines) shallow enough to cross, but you'll get 5 meters further behind for every 10 meters of river you cross. Assume the thief is too terrified to consider moving back towards the left side of the map.
Given the starting and ending locations, and the positions of (both ends of) the N crossings, i want an algorithm to find whether it is possible for the thief to escape, i.e., to reach the end location before you catch up.
i am struggling on how to approach this problem .. any ideas are highly appreciated ..thanks
figure
It's a bit unclear what exactly is needed here, but here's an outline of an approach to solve this problem:
You need to create an acyclic graph from the picture given with two sets of weights, one for you and one for the thief that represents how much time it takes each of you to travel that far (or alternatively, two acyclic graphs with the same shape but different weights):
Make nodes/vertexes out of: the starting and ending (timewarp) points, the entry points to every bridge and the exit points from every bridge.
Make edges that connect the entry point vertices of every bridge to their own exit point vertices. Set the thief's edge-weights to the length of the bridge and set yours to 1.5 times that.
Make edges from the starting point vertex to the entry points of every bridge that crosses the first river.
Make edges from the exit point vertices of every bridge over the first river to the entry point vertices of every bridge over the second river.
Repeat step 4 until you get to the last river.
Make edges from the exit point vertices of every bridge over the last river to the timewarp's vertex.
For every non-bridge edge, set the thief's weights equal to their length, and set your weights to half that.
Now, you can use A* search algorithm to determine how long it takes the their and you to get to the timewarp. Whoever would get there first wins.
For A* you need some kind of global maximum distance estimating function, if you cannot derive something for that, just use a maximum possible distance for every thing. If you do this, A* devolves into Djikstra's algorithm, which still works but is slower.

shortest path to surround a target in a weighted 2d array

I'm having some trouble finding the right approach to coding this.
Take a random-generated 2d array, about 50x50 with each cell having a value 1~99.
Starting at a random position "Green", and the goal is to surround the target "Red" with the lowest amount of actions.
Moving to a neighboring cell takes 1~99 actions depending on it's value.
example small array with low values:
[
Currently the best idea i have is, generate 4 sets of checkpoints based on the diagonals of the target and then using a lot of Dijkstra's to find a path that goes through all of them, as well as the starting point.
One problem i have is this very quickly becomes an extreme numbers of paths.
FROM any starting point "NorthWest-1 to NW-20" TO any ending point in "NE-1 to NE-20", is 400 possibilities. Adding the 3rd and 4th diagonal to that becomes 400 * 20 * 20.
Another problem using diagonal checkpoints is that the problem is not [shortest path from green to a diagonal (orange path)]
[
but rather from "green to any point on the path around red".
Current pseudocode;
take 2 sets of diagonals nearest to Green/start
find the shortest path that connects those diagonals while going through Green
(backtracking through the path is free)
draw a line starting from the target point, in-between the 2 connected diagonals,
set those cells to value infinite to force going around them (and thus around the target)
find the shortest path connecting the now-seperated diagonals
Unfortunately this pseudocode already includes some edge cases where the 'wall' blocks the most efficient path.
If relevant, this will be written in javascript.
Edit, as an edge case it could spiral the target before surrounding, though extremely rare
Edit2; "Surround" means disconnect the target from the rest of the field, regardless of how large the surrounded area is, or even if it includes the starting point (eg, all edges are 0)
Here is another larger field with (probably) optimal path, and 2 fields in text-form:
https://i.imgur.com/yMA14sS.png
https://pastebin.com/raw/YD0AG6YD
For short, let us call paths that surround the target fences. A valid fence is a set of (connected) nodes that makes the target disconnected from the start, but does not include the target. A minimal fence is one that does so while having a minimal cost. A lasso could be a fence that includes a path to the start node. The goal is to build a minimal-cost lasso.
A simple algorithm would be to use the immediate neighborhood of the target as a fence, and run Dijkstra to any of those fence-nodes to build a (probably non-optimal) lasso. Note that, if optimal answers are required, the choice of fence actually influences the choice of path from the start to the fence -- and vice-versa, the choice of path from start to fence can influence how the fence itself is chosen. The problem cannot be split neatly into two parts.
I believe that the following algorithm will yield optimal fences:
Build a path using Dijkstra from start to target (not including the end-points). Let us call this the yellow path.
Build 2 sets of nodes, one on each side of this yellow path, and neighboring it. Call those sets red and blue. Note that, for any given node that neighbors the path, it can either be part of the path, blue set, red set, or is actually an end-point.
For each node in the red set, run Dijkstra to find the shortest path to a node in the blue set that does not cross the yellow path.
For each of those previous paths, see which is shortest after adding the (missing) yellow-path bit to connect the blue and red ends together.
The cost is length(yellowPath) * cost_of_Dijkstra(redStart, anyBlue)
To make a good lasso, it would be enough to run Dijkstra from the start to any fence node. However, I am unsure of whether the final lasso will be optimal or not.
You might want to consider the A* search algorithm instead, you can probably adjust the algorithm to search for all 4 spots at once.
https://en.wikipedia.org/wiki/A*_search_algorithm
Basically A* expands Dijkstra's algorithm by focusing it's search on spots that are "closer" to the destination.
There are a number of other variations for search algorithms that may be more useful for your situation as well in the "Also See" section, though some of them are more suited for video game path planning rather than 2D grid paths.
Edit after reviewing question again:
Seems each spot has a weight. This makes the distance calculation a bit less straightforward. In this case, I would treat it as an optimization. For the heuristic cost function, it may be best to just use the most direct path (diagonal) to the goal as the heuristic cost, and then just use A* search to try to find an even better path.
As for the surround logic. I would treat that as it's own logic and a separate step (likely the second step). Find least cost path to the target first. Then find the cheapest way to surround the path. Honestly, the cheapest way to surround a point is probably worth it's own question.
Once you have both parts, it should be easy enough to merge the two. There will be some point where the two first overlap and that is where they are merged together.

Shortest path in a maze

I'm developing a game similar to Pacman: consider this maze:
Each white square is a node from the maze where an object located at P, say X, is moving towards node A in the right-to-left direction. X cannot switch to its opposite direction unless it encounters a dead-end such as A. Thus the shortest path joining P and B goes through A because X cannot reverse its direction towards the rightmost-bottom node (call it C). A common A* algorithm would output:
to get to B from P first go rightward, then go upward;
which is wrong. So I thought: well, I can set the C's visited attribute to true before running A* and let the algorithm find the path. Obviously this method doesn't work for the linked maze, unless I allow it to rediscover some nodes (the question is: which nodes? How to discriminate from useless nodes?). The first thinking that crossed my mind was: use the previous method always keeping track of the last-visited cell; if the resulting path isn't empty, you are done. Otherwise, when you get to the last-visited dead-end, say Y, (this step is followed by the failing of A*) go to Y, then use standard A* to get to the goal (I'm assuming the maze is connected). My questions are: is this guaranteed to work always? Is there a more efficient algorithm, such as an A*-derived algorithm modified to this purpose? How would you tackle this problem? I would greatly appreciate an answer explaining both optimal and non-optimal search techniques (actually I don't need the shortest path, a slightly long path is good, but I'm curious if such an optimal algorithm running as efficiently as Dijkstra's algorithm exists; if it does, what is its running time compared to a non-optimal algorithm?)
EDIT For Valdo: I added 3 cells in order to generalize a bit: please tell me if I got the idea:
Good question. I can suggest the following approach.
Use Dijkstra (or A*) algorithm on a directed graph. Each cell in your maze should be represented by multiple (up to 4) graph nodes, each node denoting the visited cell in a specific state.
That is, in your example you may be in the cell denoted by P in one of 2 states: while going left, and while going right. Each of them is represented by a separate graph node (though spatially it's the same cell). There's also no direct link between those 2 nodes, since you can't switch your direction in this specific cell.
According to your rules you may only switch direction when you encounter an obstacle, this is where you put links between the nodes denoting the same cell in different states.
You may also think of your graph as your maze copied into 4 layers, each layer representing the state of your pacman. In the layer that represents movement to the right you put only links to the right, also w.r.t. to the geometry of your maze. In the cells with obstacles where moving right is not possible you put links to the same cells at different layers.
Update:
Regarding the scenario that you described in your sketch. It's actually correct, you've got the idea right, but it looks complicated because you decided to put links between different cells AND states.
I suggest the following diagram:
The idea is to split your inter-cell AND inter-state links. There are now 2 kinds of edges: inter-cell, marked by blue, and inter-state, marked by red.
Blue edges always connect nodes of the same state (arrow direction) between adjacent cells, whereas red edges connect different states within the same cell.
According to your rules the state change is possible where the obstacle is encountered, hence every state node is the source of either blue edges if no obstacle, or red if it encounters an obstacle (i.e. can't emit a blue edge). Hence I also painted the state nodes in blue and red.
If according to your rules state transition happens instantly, without delay/penalty, then red edges have weight 0. Otherwise you may assign a non-zero weight for them, the weight ratio between red/blue edges should correspond to the time period ratio of turn/travel.

Shortest Path, but on a physical maze

I'm implementing a robot to be able to solve any maze (where the robot only has front sensors, but I make it scan the surroundings), and I was able to get it to turn the maze into a map where 0 represents walls, and 1 represents roads, with possibly slanted roads. Now, the robot is not fast at turning, but fairly fast at moving down a straight line. Therefore, a normal shortest path algorithm through the somewhat slanted hallway would be slow, although the paths are wide enough for it.
For example, we find
0001111111000
0011111110000
0111111100000
1111111000000
1111110000000
As a possible map. I'd like the robot to recognize that it can walk diagonally, or even just go straight up then right then right again, instead of turning every time in a normal shortest path algorithm.
Any ideas? Also, a complete algorithm change is welcome too - I'm fairly new to this.
I've faced similar problem some time ago.
You can assign weights to surrounding cells and less weight to the front cell, thus making a weight graph that is made during the movement.
I used Dijkstra algorithm with weights of 2 for surrounding cells and weight 1 for the front cell, you must pass direction of robot to Dijkstra and when adding them to the priority queue, and when extracting cells from the queue add the neighbors with respect to the direction saved in the extracted cell.
Then make the move and then recompute the modified Dijkstra for finding the nearest unseen cell.

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.

Resources