Is there any algorithm to find overlapping edges in a graph? - algorithm

I'm solving extended version of knight tour problem, in which program has to return maximum number of cells through which knight can come back to initial position without overlapping its path.
I'm using backtracking approach but got stuck in detecting overlapping.

A graph is defined as a set of vertices plus a set of edges, where an edge is a pair of distinct vertices.
In particular, there is no notion of two edges "intersecting" in the way that you mean, because that's a consequence of how you've chosen to draw the graph — where you've drawn the vertices on the plane — rather than a property of the graph itself. (There is a concept of a "planar graph", meaning a graph that can be embedded in the plane with no edges intersecting; but your graph is a planar graph in that sense, so it's not really what you want.)
So to determine if two line segments intersect, we're outside the area of graph theory. Fortunately, there are some pretty straightforward ways to do this; I see that How can I check if two segments intersect? lists several. The approach that came first to my mind (and is used by a few of the highest-voted answers there) is to observe that line segments AB and CD intersect if and only if ∠CAB and ∠BAD have the same sense (clockwise vs. counterclockwise; this means that C and D are on opposite sites of AB) and ∠ACD and ∠DCB have the same sense (this means that A and B are on opposite sides of CD). You can determine this by taking the cross-products of the various segments CA, AB, etc., and comparing signs (positive vs. negative). If your coordinates are all integers, then this just requires a bit of integer arithmetic.

If this problem is restricted to knight moves, then we can consider that the number of ways that knight moves can intersect is limited (at most 9, not considering direction). For instance, if we have (on a standard chessboard) the move d3-e5, then the only knight moves that intersect are: e2-e4, c3-e4, e3-c4, e3-d5, f3-d4, d4-f5, e4-c5, e4-d6, and f4-d5 -- again, without considering direction. Near the edge of the board there would of course be fewer of those.
This means that you can spend constant time per move to mark those potentially crossing edges as no longer available, and continue the search only along available edges. To allow backtracking, you save on the (recursion) stack which edges you made unavailable at which move.

Related

How to compute the set of polygons from a set of overlapping circles?

This question is an extension on some computation details of this question.
Suppose one has a set of (potentially overlapping) circles, and one wishes to compute the area this set of circles covers. (For simplicity, one can assume some precomputation steps have been made, such as getting rid of circles included entirely in other circles, as well as that the circles induce one connected component.)
One way to do this is mentioned in Ants Aasma's and Timothy's Shields' answers, being that the area of overlapping circles is just a collection of circle slices and polygons, both of which the area is easy to compute.
The trouble I'm encountering however is the computation of these polygons. The nodes of the polygons (consisting of circle centers and "outer" intersection points) are easy enough to compute:
And at first I thought a simple algorithm of picking a random node and visiting neighbors in clockwise order would be sufficient, but this can result in the following "outer" polygon to be constructed, which is not part of the correct polygons.
So I thought of different approaches. A Breadth First Search to compute minimal cycles, but I think the previous counterexample can easily be modified so that this approach results in the "inner" polygon containing the hole (and which is thus not a correct polygon).
I was thinking of maybe running a Las Vegas style algorithm, taking random points and if said point is in an intersection of circles, try to compute the corresponding polygon. If such a polygon exists, remove circle centers and intersection points composing said polygon. Repeat until no circle centers or intersection points remain.
This would avoid ending up computing the "outer" polygon or the "inner" polygon, but would introduce new problems (outside of the potentially high running time) e.g. more than 2 circles intersecting in a single intersection point could remove said intersection point when computing one polygon, but would be necessary still for the next.
Ultimately, my question is: How to compute such polygons?
PS: As a bonus question for after having computed the polygons, how to know which angle to consider when computing the area of some circle slice, between theta and 2PI - theta?
Once we have the points of the polygons in the right order, computing the area is a not too difficult.
The way to achieve that is by exploiting planar duality. See the Wikipedia article on the doubly connected edge list representation for diagrams, but the gist is, given an oriented edge whose right face is inside a polygon, the next oriented edge in that polygon is the reverse direction of the previous oriented edge with the same head in clockwise order.
Hence we've reduced the problem to finding the oriented edges of the polygonal union and determining the correct order with respect to each head. We actually solve the latter problem first. Each intersection of disks gives rise to a quadrilateral. Let's call the centers C and D and the intersections A and B. Assume without loss of generality that the disk centered at C is not smaller than the disk centered at D. The interior angle formed by A→C←B is less than 180 degrees, so the signed area of that triangle is negative if and only if A→C precedes B→C in clockwise order around C, in turn if and only if B→D precedes A→D in clockwise order around D.
Now we determine which edges are actually polygon boundaries. For a particular disk, we have a bunch of angle intervals around its center from before (each sweeping out the clockwise sector from the first endpoint to the second). What we need amounts to a more complicated version of the common interview question of computing the union of segments. The usual sweep line algorithm that increases the cover count whenever it scans an opening endpoint and decreases the cover count whenever it scans a closing endpoint can be made to work here, with the adjustment that we need to initialize the count not to 0 but to the proper cover count of the starting angle.
There's a way to do all of this with no trigonometry, just subtraction and determinants and comparisons.

The shortest path between two points on a cuboid on its surface

I can't find a universal solution to "The Spider and the Fly Problem" (the shortest path between two points on a cuboid on its surface). Everybody solves a one specific case but what when two points can be anywhere?
My idea was to create an algorithm that considers various nets of a cuboid, calculates shortest paths on 2D and then returns the minimum but I have no idea for the algorithm to generate these grids (I guess hardcoding all combinations is not the best way).
Simplistic approach (only works where the points are on the same or adjacent faces)
Flatten the cube structure to 2d as follows...
Start with a face containing one of the two points. If this also contains the other point, you can stop there and the solution is trivial.
There are only 4 neighbouring faces. If any of them contain the other point, you can place that face adjoining the first, and plot the straight line.
Otherwise, then the points are on opposing faces. You need to try placing the final face adjoining each of the 4 neighbouring faces, and choose the shortest of the 4 alternatives. This will not always give the best solution, but it's not far off, and is cheap.
Generic approach
Jim Propp's surface distance conjecture is that For a centrally symmetric convex compact body, the greatest surface distance between two points is achieved only for pairs which are opposites through the centre. My conjecture based on that would be that the shortest distance is approximately where the plane made by the two points and the centre of the body meets the surface. So you simply need to find where that plane intersects the faces using 3d geometry, and use the faces that are crossed by the shorter of the two alternatives when looking at possible routes. If the plane runs along an edge of the cube (e.g. if the points are on opposite faces and are both between the centre of the face and the corner of the face, and those corners are linked by an edge) then routes through both faces should be considered, although I speculate they will be equivalent lengths.
This solution is more generic, and also satisfies scenarios where the points are on the same face, connected faces and opposite faces.
The only problem with this approach arises where the line between the two points passes through the centre of the body, which by definition means that the two points are exactly opposite each other, because that means the 3 points are in a straight line, so there isn't a plane...
I think this is a good question, for which the answer is not at all obvious. In the smooth realm, it is an extraordinarily difficult problem. Geodesics (shortest paths) on a sphere (which is a smooth analog of a cube) are easy to find. Geodesics on a biaxial ellipsoid (an ellipsoid of revolution; one cross section is a circle) are much harder to find. Finding geodesics on a triaxial ellipsoid (a smooth analog of a general cuboid) was a challenging unsolved problem in the first half of the 19th century. See the Wikipedia page.
On the other hand, geodesics on cuboid are made from straight line segments so are much simpler. But some of the difficulty of the problem remains.
You may be able to find some literature on the subject if you search for the term "net". A polyhedron cut along some edges so that it can be flattened is often called a "net". I was able to quickly find a site that claims (without proof) that there are just 11 different nets for a cub(oid). But I agree with you that hard coding all the variations is not the best way.
It's not even obvious to me that the approach using nets will work for all polyhedra. I think I see an argument that will work for cuboids, but for general polyhedra, even convex polyhedra, it is not known whether they must have even one net. See the Wikipedia page. I think a satisfying solution to the problem on cuboids should work more generally on polyhedra, and the net idea seems to be insufficiently general, in my view.
What I'm thinking might work is a dynamic programming solution, where you look at the different edges your path can pass through between the initial and final points. There is a hierarchy of edges (those on the starting face; those containing a vertex on the starting face; those on the faces adjacent to the starting face; etc.). For each point on each of those edges you can find the minimum distance to the start point, culminating in the minimum distance from the end point to the start point.
Another way to think about this is to use something akin to the reflection principle, except instead of reflections, we use rotations in space which rotate the polyhedron about one of its edges so that the other face adjacent to the edge becomes coplanar with the starting face. Then we don't have to worry about whether we have a good net or not. You just pick a sequence of edges so that the final point is eventually rotated onto the plane of the initial face. The sequence of edges is finite because any loop is not part of a minimal path. I'll think about how I might be able to communicate this idea better.
I solved the problem for cubes and cuboids by discretizing the cube edges, generating a big graph and solving graph shortest path problem. You can specify start point (sx, sy, 0), and algorithm will determine all shortest path to target points on top face (z = 1), here for 19 * 19 target points. Cube edges are divided into 100 parts. Graph with these settings has n=1558 vertices and m=464000(!) edges, inner loop of floyd_warshall_path() for updating shortest path distances is executed n³ = 3,781,833,112 times (takes less than 1 minute on Raspberry Pi400). Orange shortest paths flow through 3 cuboid faces, blue ones through 4. Algorithm generates OpenSCAD file as output. Details in this posting, all code in GitHub repo.
P.S:
I made experiments with 1 x 1 x 3 cuboid and was able to find examples where shortest path between two points needs to pass 5 faces. Code is submitted to GitHub repo, and details are in this forum posting.
Orange shortest paths are passing 3 faces, blue are passing 4 faces, and the new yellow shortest paths pass 5 faces! With "mirror" at bottom, allowing to see the bottom face with start point as well. This time cuboid edges are divided into 150 parts (149 inner vertices), and there are 49 * 49 top face target points for single start point on bottom face:
I implemented cuboid shortest paths completely different this time, no graph, and geometric distance calculations in 28 possible foldings of cuboid into plane, details in this new forum thread:
Efficient cuboid surface shortest path problem application
The much increased efficiency with all the sliders allows to change x/y coordinate of bottom face point, number of divisions in X/Y direction and which folding to display, with instantaneous display after any change. This allows to play with a cuboid and "see" how the shortest paths change (on top face as well as on side and bottom faces).
Scale to 50% size, 0.5fps animation shows the 6 foldings containing any shortest path. The animation corresponds to clockwise traversal of OpenSCAD 3D top face shown on the right.
With added top and bottom face view.
but for anyone still interested, this question was solved on stackxechange by "Intelligenti pauca" (with some nice diagrams): here is the original link
https://math.stackexchange.com/questions/3023721/finding-the-shortest-path-between-two-points-on-the-surface-of-a-cube
The "Simplistic approach" from "Richardissimo" was on the right track, you just need to check a few more cases.
Intelligenti pauca:
If the two points belong to adjacent faces, you have to check three
different possible unfoldings to find the shortest path. In diagram
below I represented the first point (red) and the second point (black)
in three possible relative positions: middle position occurs when the
path goes through the common edge, in the other cases the path
traverses one of the faces adjacent to both faces. The other possible
positions are clearly longer than these.
image1
If the two points belong to opposite faces, then 12 different possible
positions have to be checked: see diagram below.
image2
After mapping the points like this you can calculate the distances like normal on a plane an have min(possible distances) as your shortest path-length.

Plotting Distance Constrained Points on a Plane

I'm crossposting this from the mathematics stack exchange at the suggestion of one user who thought somebody here with experience in embedding algorithms might be able to help, though it should be noted that I'm not trying to do a strict graph embedding (which would not allow for vertices to intersect).
Does anybody know of some algorithmic way to tell if it is possible to plot a set of distance constrained points on a cartesian plane. Or, better still, a method to determine the minimum number of dimensions required to accurately depict the points.
As an example: If you have three points and a constraint that says they are all one unit away from each other, you can plot this easily on a cartesian plane as an equilateral triangle.
However, if you have the constraints A->B = 1, A->C = 1, and B->C = 3 then you will not be able to plot these points while maintaining their distances.
However in my case I have a graph with many more than three vertices. The graph is definitely non-planar: one such case involves 1407 vertices all of which are connected by a weighted bidirectional edge that defines the "distance" between the two vertices.
The question is, is there some way to tell if I can depict this graph with accurate distances on a cartesian plane. I know I can't depict it without edges crossing, but I don't care about doing that. I just want the points on the plane an appropriate distance from each other.
Additional information about the graph in case it helps:
1) Each node represents a set of points. 2) The edge weights are derived by optimally overlaying the point sets from each pair of nodes and then taking the RMSD of the resulting point sets. 3) The sets of points represented by any two nodes can be paired with each other. That is, we can think of each node as a set of 8 points numbered 1-8. This numbering is static. When I overlay node A and node B, the points are numbered identically to when I overlay A and C and B and C.
My thoughts: Because RMSD is a metric on R^3 (At least I believe so. This paper claims to prove it http://onlinelibrary.wiley.com/doi/10.1107/S0108767397010325/abstract), it should be possible for me to do this in R^3 at the very least.
As my real goal here is to turn this set of points into a nice figure, a three dimensional depiction would actually suffice, as I could depict the 3D figure in 2D. I also recognize that numerical instability in the particular optimal overlay algorithm I'm using will cause issues, but I'm interested in the answer for an ideal case.

Set operations (union and intersection) on simple polygons in 2D

I am looking for an algorithm for union and intersection operations on simple polygons in 2D.
Every polygon in my application is:
defined by a set of points (point is defined by x and y coordinates),
convex or concave (non-convex),
not self-intersecting,
without holes.
I met two approaches. The first is algorithm that indicates intersection points as entry or exit.
By K. Hormann and G. Greiner [ http://www.inf.usi.ch/hormann/papers/Greiner.1998.ECO.pdf ].
I very like this approache, but there is problem with degeneracies (shared edges, touching verticies).
I also read solution for degeneracies: [ http://arxiv.org/pdf/1211.3376.pdf ]. But I think that this solution returns wrong result for situations like this:
The second algorithm divides edges at intersection points and then select the "right" edges for selected operation.
By F. Martinéz et al. [ http://www.cs.ucr.edu/~vbz/cs230papers/martinez_boolean.pdf ].
But this algorithm returns one polygon instead two triangles for this situation (operation: intersection, point F lies on edge AB):
Can you please refer me to another approache? (Polygons usually have a little edges, so efficiency is not in the first place.)
I would like to use some algorithm instead existing library.
I recommend the following approach: for every vertex of a polygon, decide once for all if it is inside or outside the other polygon. The intersections points between edges tell you where the "insideness" state changes, and this allows you to delimit the fragments of both polygon outlines that you need to reassemble (for instance Out(P, Q) and Out(Q, P) are the fragments for the union, while In(P, Q) and In(Q, P) are those for the intersection).
Now to achieve good robustness at a little cost, use a coherence principle: the number of intersections along an edge must have a parity compatible with the insideness at both endoints. For instance, when joining an inside vertex to an outside vertex, you must find an odd number of intersections.
When you observe a deviation from this rule, modify the parity of the number of intersections. This can be done by discarding an intersection, or by duplicating one.
This measure will not avoid unwanted effects like very close edges not merging or microscopic intersections, but it will avoid catastrophic anomalies. It will work even with poor insideness tests or inaccurate intersection function.

How can I pick a set of vertices to subtract from a polygon such that the distortion is minimum?

I'm working with a really slow renderer, and I need to approximate polygons so that they look almost the same when confined to a screen area containing very few pixels. That is, I'd need an algorithm to go through a polygon and subtract/move a bunch of vertices until the end polygon has a good combination of shape preservation and economy of vertice usage.
I don't know if there's a formal name for these kind of problems, but if anyone knows what it is it would help me get started with my research.
My untested plan is to remove the vertices that change the polygon area the least, and protect the vertices that touch the bounding box from removal, until the difference in area from the original polygon to the proposed approximate one exceeds a tolerance I specify.
This would all be done only once, not in real time.
Any other ideas?
Thanks!
You're thinking about the problem in a slightly off way. If your goal is to reduce the number of vertices with a minimum of distortion, you should be defining your distortion in terms of those same vertices, which define the shape. There's a very simple solution here, which I believe would solve your problem:
Calculate distance between adjacent vertices
Choose a tolerance between vertices, below which the vertices are resolved into a single vertex
Replace all pairs of vertices with distances lower than your cutoff with a single vertex halfway between the two.
Repeat until no vertices are removed.
Since your area is ultimately decided by the vertex placement, this method preserves shape and minimizes shape distortion. The one drawback is that distance between vertices might be slightly less intuitive than polygon area, but the two are proportional. If you really wish, you could run through the change in area that would result from vertex removal, but that's a lot more work for questionable benefit imo.
As mentioned by Angus, if you want a direct solution for the change in area, it's not actually super difficult. Was originally going to leave this as an exercise to the reader, but it's totally possible to solve this exactly, though you need to include vertices on either side.
Assume you're looking at a window of vertices [A, B, C, D] that are connected in that order. In this example we're determining the "cost" of combining B and C.
Calculate the angle offset from collinearity from A toward C. Basically you just want to see how far from collinear the two points are. This is |sin(|arctan(B - A)| - |arctan(C - A)|)| Where pipes are absolute value, and differences are the sensical notion of difference.
Calculate the total distance over which the angle change will effectively be applied, this is just the euclidean distance from A to B times the euclidean distance from B to C.
Multiply the terms from 2 and 3 to get your first term
To get your second term, repeat steps 2 - 4 replacing A with D, B with C, and C with B (just going in the opposite direction)
Calculate the geometric mean of the two terms obtained.
The number that results in step 6 presents the full-picture minus a couple constants.
I tried my own plan first: Protect the vertices touching the bounding box, then remove the rest in the order that changes the resultant area the least, until you can't find a vertice to remove that keeps the new polygon area within X% of the original one. This is the result with X = 5%:
When the user zooms out really far these shapes fit the bill well enough for me. I haven't tried any of the other suggestions. The savings are quite astonishing, sometimes from 80-100 vertices down to 4 or 5.

Resources