Professor Adam's Kids (determine the maximum-flow) - algorithm

I need help in understanding how to solve the following problem:
Professor Adam has two children who, unfortunately, dislike each other. The problem is so severe that not only do they refuse to walk to school together, but in fact each one refuses to walk on any block that the other child has stepped on that day. The children have no problem with their paths crossing at a corner. Fortunately both the professor's house and the school are on corners, but beyond that the professor is not sure if it is going to be possible to send both of the children to the same school. The professor has a map of the town. Show how to formulate the problem of determining whether both the children can go to the same school as a maximum-flow problem.
The only thing I can think of is to have a four corner graph. The upper left-hand vertex represents the source (Adam's house) and the lower right-hand corner represents the sink (school). The corner x on the upper right-hand corner represents a corner in the neighborhood while y represents the lower left-hand corner of the neighborhood. Thus, we have paths going from S -> C1, S -> C2, C1 -> t, and C2 -> t. Each path has a weight of 1 since it can only accommodate one child. The max flow of this graph is 2 which proves that they can attend the same school.
The problem I am having is that I am not sure if this solution that I've arrived upon satisfies the problem. The part that is stumping me the most is that I am not sure what this means: but in fact each one refuses to walk on any block that the other child has stepped on that day. How can this statement make sense if both live in the same house on the same block?

UPDATE: turned out, I misread the problem. The problem asks to find "edge-disjoint" paths, not vertex-disjoint paths. In this case the solution is just to represent each corner as a vertex, each block as an edge with capacity one, and run regular max flow (as correctly suggested by Curious below).
I believe that that OP has the same confusion based on
but in fact each one refuses to walk on any block that the other child has stepped on that day. How can this statement make sense if both live in the same house on the same block?
Note that children live in the same house on the same corner, not on the same block.
I leave the rest of the answer in case someone one day is actually looking for the vertex disjoint problem:
If I understand the problem correctly, what it asks is to find two vertex-disjoint paths from source to sink. Just using graph as is, and assigning capacity of 1 to each edge is not enough. Consider the following example:
s -> C1, C1 -> C3, C3 -> C4, C4 -> t
s -> C2, C2 -> C3, C3 -> C5, C5 -> t
If you assign capacity of 1 to each of these edges, and run any max flow algorithm, it will find a max flow of 2, but there's no two vertex-disjoint paths (both paths would go through vertex C3).
To address it, you need to adjust your graph. For each vertex except s and t, split it in two. Say vertex u was split into u' and u''. Make all the edges that were going into u go into u', and all the edges that were going from u go from u'' (the capacity of those edges does not matter, as long as it is positive, so you can set it to 1). Finally, add an edge from u' to u'' with capacity 1, and run max flow on this graph. Because of those edges we added between split nodes, each vertex will be used at most once, because for the vertex to be used we need to enter u', go from u' to u'' and exit from there, and only one unit of flow can go from u' to u''.

Lets keep it simple ..
First things First.Why did you restrict only to 2 corners other than his house and school . It was not mentioned that way in the problem .
Modelling of Adam's Problem could go like this
Vertices : all corners of town
Directed edges : all roads connecting the corners in both directions i.e if we have 2 corners p,q then we would have edge from p to q as well as from q to p
for all edges (u,v) , c(u,v)=1
Now solve the max flow problem and if it is >= 2 , Adam is lucky .

I've never heard of a max-flow problem, so this is what I gather from wikipedia.
It seems like the graph (V,E) should have one vertex for each intersection of streets and one edge for each street (between intersections). Then each edge would have capacity 1 (as you say). Of course, if one of the children makes it to the school, they can also make it back home (using the analogous path in the "opposite graph" where all the edges are reversed).
Then the only ambiguity is: what should the direct of an edge be? If the graph does not have to be directed, this could work as the formulation of the problem.

Wikipedia
Since the question specifies that the house (s) and school (t) both are on corners, I assume that corners don't count as "walking on a block" and the question says they have no problems crossing paths at a corner, so for instance they could both cross the street to another block together, as long as only one of them took the sidewalk to another corner and the other immediately crossed the street to another block.
In that case, the limiting factor in the flow is blocks, so they must become edges in the flow diagram with capacity of 1. But what do they connect? They have to connect to other blocks. So imagine a square of 9 blocks:
1 2 3
4 5 6
7 8 9
With the house at the southeast corner of 1 and the school at the southeast corner of 5. Both children could cross the street to block 5, but only one can walk around block 5 to get to the school at the opposite corner. The other one might as well cross to block 4, then to 7, then to 8 where he can cross the street to the school on the corner of block 5.
So the house (s) can get to blocks 1, 2, 4, and 5. The school can be gotten to from 5, 6, 8 or 9. My first thought is to model each block as two nodes, input and output, and an edge with a capacity of 1 connecting the input to the output. Other nodes will be linked with edges that have a capacity of at least 2. You also need nodes for s and t. Link s to the inputs of 1, 2, 4, and 5 and the outputs of 5, 6, 8, 9 go to t. Then link the block outputs up to the inputs of any block you can get to from a corner, i.e. output of 1 goes to inputs of 2, 4, 5 and outputs of 2, 4, 5 goes to the input of 1 as well.
A simpler way to think of it might be that each corner is a node connected to the inputs of the blocks around it and the outputs of the blocks around it connected into the corner node. All edges should have a capacity of at least two though, except the ones connecting block inputs and outputs which have a capacity of 1. That way the limiting factor is "walking on a block". As long as the flow is 2 at the end, they can make it.
So let's simplify the diagram and get rid of the blocks we won't be using. One child can walk around block 5 from s to t, the other can cross the street to 4, then cross to block 8 at corner a and walk along block 8 to corner t where the school is:
s
4 5
a t
8
Here are the edges:
s->4in (capacity 2)
s->5in (capacity 2)
4in->4out (capacity 1) // limiter
5in->5out (capacity 1) // limiter
8in->8out (capacity 1) // limiter
4out->s (capacity 2)
4out->a (capacity 2)
5out->s (capacity 2)
5out->a (capacity 2)
5out->t (capacity 2)
8out->a (capacity 2)
8out->t (capacity 2)
a->4in (capacity 2)
a->5in (capacity 2)
a->8in (capacity 2)
One child's path s->5in->5out->t
Other child's path s->4in->4out->a->8in->8out->t

I was also looking for solution and found this and it does appear correct to me.
http://www.repond.ch/ressources/cse/algorithme/week10/exercise7-sol.pdf?PHPSESSID=col0hua0ehpk57givsva99mco4
"Let us model the city map with a graph G(V,E) in the following way: V contains each corner in the town and E contains the roads. More specifically, we assume there is an edge between two nodes u,v belongs to V
if there is a road connecting the corners u and v in the city. We assume each edge has a capacity of 1. Furthermore, let the house of Professor Adam be
the source, s, and the school be the sink, t. Now we can formulate the problem as a max-flow problem: the flow on edge (u, v) will represent if any of the children has stepped on the road connecting the corners u and v. Furthermore, we let only integral flows so f(u, v) = 1 in this case. Therefore, since the capacity of each edge in the graph is c(u, v)= 1, if a flow is passing over one link, that link can not be used anymore. which means the other kid will not take that road to go to school. Now if both of the kids can go to school, it means that there is flow from the source (house) to the sink (school) with value at least 2. Likewise if one could find a maximal
integral flow in G from s to t that has a value of at least 2, then both children can go to school. Otherwise, it won’t be possible."

Related

Graph theory: best algorithm to find combination of edges “directions”, where each node has at most one edge directed to it

I’m dealing with a graph where there are a certain number of nodes, and there are predefined connections between them which don’t have “directions” yet.
Problem is to give all the edges a direction (ex. If there’s a connection between A And B, give this edge the A->B direction, or B->A), in a way that no node is at the receiving end of more than one edge.
Examples:
For this model (A-B-C), A->B->C works, but A->B<-C does not work, as B is at the receiving end of more than one connection. Although A<-B->C works, as B is on the giving end of both of its connections.
I’ve tried loop detection, but the fact that these nodes can be arbitrarily connected to one another, there can be numerous loops which may or may not be directly attached to each other, I could not find a solution to make use of the information.
Number of nodes can be north of thousands, and connections can be many hundreds in my case. This also rules out brute force.
It is not guaranteed that there will be a definite solution, the aim of the algorithm is to find a combination where there’s the least number of connections causing nodes to have more than one edge pointing to them.
Not a complete algorithm, but given your description of the problem in the comments, I feel like these steps will probably bring the problem back into the brute-forcible range.
First, you should "trim" your graph. Any nodes of degree one should be pruned, with their connected edge being directed at the pruned node. Since no other edge can point to that node, we know that this choice is optimal. Rinse and repeat until all nodes remaining have two or more edges.
Next, as you mentioned, you should exclude any isolated nodes. You can actually extend this up to connected components of size <= 3. This is because for up to three nodes, your number of edges cannot exceed the number of nodes, so you can randomly assign one edge, and the rest will fall into place.
Now, what will remain are a bunch of large, highly-connected, connected components. You could actually do one more check and see if any of these form a single cycle (all nodes degree two) and then assign one edge randomly, but this is probably a fairly rare case. You'll probably just want to start brute forcing each of these independently. It'd probably be best to start from the nodes with the smallest number of edges first, updating the degree of nodes as you assign edges (and also pruning any degree one edges as before), backtracking as necessary.
This is a continuation of the answer by Dillon Davis.
After tree-like branches are removed, and simple cycles are resolved, the remaining graph has nodes of degree 2 or more. I propose that (for the purposes of analyzing the graph) all of the nodes of degree 2 can be removed.
Allow me to explain by example. In this example, when a node is represented by a number, that number is the degree of the node. When a node is represented by a letter, that node has degree 2. So the graph
3 - A - B - C - 4
represents a node of degree 3, connected to a chain of nodes of degree 2, connected to a node of degree 4.
The two ideal choices for this section of the graph are
3 -> A -> B -> C -> 4
3 <- A <- B <- C <- 4
These are ideal in the sense that each lettered node has exactly one incoming edge. I propose that these aren't just ideal choices, they are the only choices. Consider the first ideal solution
3 -> A -> B -> C -> 4
If node 4 has too many incoming edges, we can reduce its count by reversing the edge to C, giving
3 -> A -> B -> C <- 4
But that hasn't improved the situation, it trades "too many edges into 4" with "too many edges into C". Subsequently reversing the edge between C and B resolves C, but breaks B. Keep reversing along the chain and eventually the connection between A and 3 is reversed, and we've arrived at the second ideal solution.
Which leads me to conclude that (for the purposes of analysis)
3 - A - B - C - 4
is equivalent to
3 - 4
So how is this useful in simplifying the problem. Consider the following graph:
When nodes A and B are removed, the remaining edge connects the top node 3 to itself, so that edge can be removed. Likewise for C and D. Which leaves a graph with a single edge. Choose either direction for that edge. Then complete the solution by choosing a direction for the simple cycle A-B-3, and independently choose a direction for the simple cycle C-D-3.
Here's another example:
In this case, removing A and B creates redundant edges between the remaining nodes. After removing the redundant edges, choose either direction for the edge. The direction of that edge determines the direction of the cycle 3-A-3, and cycle 3-B-3.
I wasn't sure about adding another answer, but the answer by user3386109 gave me insight into what I believe is the complete solution, and I felt that it differs too drastically from the spirit of my original answer to include as an edit.
To recap, we have a few tools under out belt:
We can prune nodes with a single edge optimally, repeating the process to completion
We can assign a direction to any edge in a simple cycle (connected components with only nodes of degree 2) and the rest will follow (optimally).
Nodes with two edges in more complex cycles can be temporarily ignored, as their edge directions will be assigned by higher degree nodes.
After reading the last point, the problem itself becomes a bit more clear. Once we have pruned the degree one nodes in bullet one, all remaining nodes have at least two edges. We can say for certain in the optimal graph that each of these nodes will have at least one directional edge pointing to them. As proof, since each node has at least two edges, but the connected component is not a simple cycle (else it would be eliminated in bullet 2), we have more edges than nodes. If any node has zero edges directed towards it, one of those edges could be reversed to reduce the number of conflicting edges, or to "free up" another node to have zero inward edges, to then do the same.
Armed with this knowledge, we know that the minimal number of conflicts (extra edges directed at nodes that already have an edge directed at them) equals the number of edges minus the number of vertices in our pruned graph. We can also conclude that as long as we manage to direct at least one edge to each node, we'll have an optimal graph, regardless of how we scatter the conflicting edges.
Originally I tried to draft an algorithm based on bullet three to accomplish this assignment, but it turns out the answer is actually a lot simpler than that even. The only way we can accidentally create a node with no edges directed away from it is by actively directing all edges away from that node. The solution is to pick a single edge in the connected component, and assign it a direction at random. Then, do a search (DFS, BFS, anything) outward from the node its directed at, assigning directions to the edges as you go, in the direction you that traverse them. Any node you reach will have an edge directed at it (the edge you took to reach it), and the root node has the edge you manually assigned to it.
In the end, this will produce a graph with the minimal number of extra edges directed at nodes. If you instead wish to minimize the number of nodes containing conflicting edges, solve the problem as stated above, and then form a subgraph of the nodes of degree three or more and their connecting edges. Solve for the minimal vertex cover of this subgraph, and then reverse the direction of the edges connecting nodes not in the minimal vertex cover yet containing conflicting edges, with those of the corresponding node in the minimal vertex cover.

What is meant by the set of all possible configuration in a given graph G

I'm trying to understand a Solved exercise 2, Chapter 3 - Algorithm design by tardos.
But i'm not getting the idea of the answer.
In short the question is
We are given two robots located at node a & node b. The robots need to travel to node c and d respectively. The problem is if one of the nodes gets close to each other. "Let's assume the distance is r <= 1 so that if they become close to each other by one node or less" they will have an interference problem, So they won't be able to transmit data to the base station.
The answer is quite long and it does not make any sense to me or I'm not getting its idea.
Anyway I was thinking can't we just perform DFS/BFS to find a path from node a to c, & from b to d. then we modify the DFS/BFS Algorithm so that we keep checking at every movement if the robots are getting close to each other?
Since it's required to solve this problem in polynomial time, I don't think this modification to any of the algorithm "BFS/DFS" will consume a lot of time.
The solution is "From the book"
This problem can be tricky to think about if we view things at the level of the underlying graph G: for a given configuration of the robots—that is, the current location of each one—it’s not clear what rule we should be using to decide how to move one of the robots next. So instead we apply an idea that can be very useful for situations in which we’re trying to perform this type of search. We observe that our problem looks a lot like a path-finding problem, not in the original graph G but in the space of all possible configurations.
Let us define the following (larger) graph H. The node set of H is the set of all possible configurations of the robots; that is, H consists of all possible pairs of nodes in G. We join two nodes of H by an edge if they represent configurations that could be consecutive in a schedule; that is, (u,v) and (u′,v′)will be joined by an edge in H if one of the pairs u,u′ or v,v′ are equal, and the other pair corresponds to an edge in G.
Why the need for larger graph H?
What does he mean by: The node set of H is the set of all possible configurations of the robots; that is, H consists of all possible pairs of nodes in G.
And what does he mean by: We join two nodes of H by an edge if they represent configurations that could be consecutive in a schedule; that is, (u,v) and (u′,v′) will be joined by an edge in H if one of the pairs u,u′ or v,v′ are equal, and the other pair corresponds to an edge in G.?
I do not have the book, but it seems from their answer that at each step they move one robot or the other. Assuming that, H consists of all possible pairs of nodes that are more than distance r apart. The nodes in H are adjacent if they can be reached by moving one robot or the other.
There are not enough details in your proposed algorithm to say anything about it.
Anyway I was thinking can't we just perform DFS/BFS to find a path from node a to c, & from b to d. then we modify the DFS/BFS Algorithm so that we keep checking at every movement if the robots are getting close to each other?
I don't think this would be possible. What you're proposing is to calculate the full path, and afterwards check if the given path could work. If not, how would you handle the situation so that when you rerun the algorithm, it won't find that pathological path? You could exclude that from the set of possible options, but I don't see think that'd be a good approach.
Suppose a path of length n, and now suppose that the pathology resides in the first step of the given path. Suppose now that this happens every time you recalculate the path. You would have to recalculate the path a lot of times just because the algorithm itself isn't aware of the restrictions needed to get to the right answer.
I think this is the point: the algorithm itself doesn't consider the problem's restrictions, and that is the main problem, because there's no easy way of correcting the given (wrong) solution.
What does he mean by: The node set of H is the set of all possible configurations of the robots; that is, H consists of all possible pairs of nodes in G.
What they mean by that is that each node in H represents each possible position of the two robots, which is the same as "all possible pairs of nodes in G".
E.g.: graph G has nodes A, B, C, D, E. H will have nodes AB, AC, AD, AE, BC, BD, BE, CD, CE, DE (consider AB = BA for further analysis).
Let the two robots be named r1 and r2, they start at nodes A and B (given info in the question), so the path will start in node AB in graph H. Next, the possibilities are:
r1 moves to a neighbor node from A
r2 moves to a neighbor node from B
(...repeat for each step unitl r1 and r2 each reach its destination).
All these possible positions of the two robots at the same time are the configurations the answer talks about.
And what does he mean by: We join two nodes of H by an edge if they represent configurations that could be consecutive in a schedule; that is, (u,v) and (u′,v′) will be joined by an edge in H if one of the pairs u,u′ or v,v′ are equal, and the other pair corresponds to an edge in G.?
Let's look at the possibilities from what they state here:
(u,v) and (u′,v′) will be joined by an edge in H if one of the pairs u,u′ or v,v′ are equal, and the other pair corresponds to an edge in G.
The possibilities are:
(u,v) and (u,w) / (v,w) is and edge in E. In this case r2 moves to one of the neighbors from its current node.
(u,v) and (w,v) / (u,w) is and edge in E. In this case r1 moves to one of the neighbors from its current node.
This solution was a bit tricky to me too at first. But after reading it several times and drawing some examples, when I finally bumped into your question, the way you separated each part of the problem then helped me to fully understand each part of the solution. So, a big thanks to you for this question!
Hope it's clearer now for anyone stuck with this problem!

How to find the optimal grid placement for least distance between nodes of a network?

If I wanted to display the nodes of a network on a 2D grid, but also I wanted to ensure the least amount of manhattan distance between any two directly connected nodes (where there is a maximum of one node per cell), what is the algorithm to do this?
To clarify, let me provide an elementary example:
A network has the following topology:
A -> B -> C
One solution of the grid placement would simply be to list the 3 items next to each other:
| A | B | C |
The distance between any two connecting nodes is 1 cell.
Suppose another network has the following topology:
A -> B -> C -> D -> A
One solution of the place for this network would be:
| A | B |
| D | C |
The distance between A and B, B and C, C and D, and D and A are each 1 cell. B and D, and A and C are not directly connected, therefore their distances do not factor into the problem.
The most optimal arrangement would be the one that provides the lowest sum distance between all directly connected nodes.
Now, how would one do this for an arbitrary network? Any help would certainly be appreciated. :)
A divide and conquer approach may bear some fruit. Consider the following algorithm:
if the cardinality of the graph is less than 10:
1) Create a 3x3 grid. Place this node of this piece of the graph on the grid in such a way that minimizes distance.
2) Return the 3x3 grid
else
1) Split the graph into two sets of nodes, recurse on each. Each recursion returns a graph of the optimal way to lay out that subset of the graph as a grid. Ideally you would find the minimum bisection for this split, but that problem is NP-hard, so perhaps an approximation?
2) Union the two subgraphs by creating a single grid with the returns of the two recursive calls next to one another. You can rotate the return of a recursive call by 90 degrees without changing it's distance sum, so there are 16 (4 orientations per) ways to union two grids. Large, but thankfully constant. Return the unioned grid that minimizes the total distance.
Clearly the factor that breaks this algorithm are the connections that span the subgrids. The rotation process only partially fixes this.
If you know your graph is planar, there's probably a way to do this optimally. Otherwise, you may be stuck with an approximation as your best solution, as for any given node with out degree > 4 you'll have to pick at least one neighbor to put at distance >= 2.
Another thing to consider is how to do the inner most step of putting <= 9 nodes on a 3x3 grid optimally. The problem is that there are probably many equally optimal ways to put the nodes on the grid in terms of the subgrid's cost, but you also want to make sure that nodes with related out-going edges (edges going out of this sub problem) are on the same side of the grid.

Finding the minimum cycle path in a dynamically directed graph

I recently came across this (Edit: Problem A) interesting problem from Spotify's hacker challenge earlier this year which involves determining the switching at train truck junctions to route a train back to it's starting point. The train must arrive facing the same direction it left and the train can never reverse on the tracks.
As I understand it, the problem can be modeled as an undirected(?) graph where we must find the shortest cycle from a certain vertex, or detect that no such cycle exists. However, the interesting part is that for a vertex, v, the vertices adjacent to v are dependent on the path taken to v, so in a sense the graph could be considered directed, though this direction is path-dependent.
My first thought was to model each node as 3 separate vertices, A, B and C, where A <-> B and A <-> C, and then use a breadth-first search to build a search tree until we find the original vertex, but this is complicated by the caveat above, namely that the adjacencies for a given vertex depend on the previous vertex we visited. This means that in our BFS tree, nodes can have multiple parents.
Obviously a simple BFS search won't be sufficient to solve this problem. I know there are algorithms that exist to detect cycles in a graph. One approach might be to detect all the cycles, then for each cycle, detect whether the path is valid. (i.e., does not reverse direction)
Does anyone else have any insights on approaches to solving this problem?
UPDATE:
I followed the approach suggested by #Karussell in the comments.
Here is my solution on github.
The trick was to model the situation using an edge-based graph, not a traditional vertex-based graph. The input file supplied in the contest is conveniently specified in terms of edges already, so this file can be easily used to build an edge-based graph.
The program uses two important classes: Road and Solver. A Road has two integer fields, j1 and j2. j1 represents the source junction and j2 represents the target junction. Each road is one-way, meaning that you can only travel from j1 to j2. Each Road also includes a LinkedList of adjacent Roads and a parent Road. The Road class also includes static methods to convert between the Strings used in the input file and integer indexes representing the A, B, and C points at each junction.
For each entry in the input file, we add two Roads to a HashMap, one Road for each direction between the two junctions. We now have a list of all of the Roads that run between junctions. We just need to connect the roads together at the junctions through the A, B and C switches. If a Road ends at Junction.A, we look up the roads that begin at Junction.B and Junction.C and add these roads as adjacencies. The buildGraph() function returns the Road whose target junction (j2) is "1A" == index 0.
At this point, our graph is constructed. To find the shortest path I simply used a BFS to traverse the graph. We leave the root unmarked and begin by queueing the root's adjacencies. If we find a road whose target junction is "1A" (index 0) then we have found the shortest cycle through the starting point. Once we reconstruct the path using each Road's parent property, it's a trivial matter to set the switches appropriately as required in the problem.
Thanks to Karussell for suggesting this approach. If you want to put your comment in answer form with a short explanation, I will accept it. Thanks to #Origin, as well. I must admit that I did not fully follow the logic of your answer, but that is certainly not to say that it is not correct. If anyone solves this problem using your solution, I would be very interested to see it.
As my comment suggested: I think that you can solve this via edge based graph or via an improvement which is more or less an 'enhanced' node based graph.
Details:
Your situation is similar to turn restrictions in road networks. Those can be modeled if you create one node per (directed!) street and connect that nodes depending on the allowed turns.
So, do not only store the position of your current position but also the direction and possible further 'situations'. To make it possible that even the same position with a 180° turn is different to your current state.
Instead of modeling your 'state' (which is directed!) into the graph you could also assign possible outcomes to every junction - now the algorithm needs to be more clever and needs to decide per junction what to do depending on your earlier state (including direction). I think, this is the main idea of the 'enhanced' node based graph which should be less memory intensive (not that important in your case).
One possible approach: first constract some kind of graph to model all connections (graph G). Then construct another graph in which we will find the cycle (graph H). For each node A in G, we will add a node to graph H. Each A node also has 2 outgoing edges (to the B and C nodes in graph G). In H, these edges will go to the next A node that would be encountered in G. For example, the A node in H corresponding to the A node of the switch with ID 3 would have an outgoing edge to node 9 and node 6 in H. The weight of each edge is the number of switches passed on that route (including the starting switch).
This will yield a graph in which we can grow a forward shortest path tree. If we would reach the start again, the cycle would be complete.
The key is that a switch is only a decision point if it is traversed in the A-> direction. It is not necessary to model the backward direction as this would only complicate the search.
edit: some more clarification
The problem consists of determining the shortest path from A to A (again). The definition of shortest is here the number of switches passed. This will be used in a Dijkstra based search algorithm. We basically are going to do Dijkstra on a graph H in which the cost of the edges is equal to the number of switches in that edge.
In the H graph, we will have a node for each switch. Each node will have 2 outgoing edges, corresponding to the 2 paths one can take (B and C directions). The edges in H will correspond to an entire route between 2 A nodes in the original graph. For the example in the problem description, we get the following:
A node corresponding to switch 1:
1 outgoing link to node 2, weight 2, corresponding to taking the C
direction when leaving switch 1. The weight is 2 because we pass switch 1 and switch 3 if we go from A1->C1->C3->A3->A2
1 outgoing link to node 3, weight 2, corresponding to taking the B direction
A node corresponding to switch 2:
1 outgoing link to node 6, weight 2, corresponding to taking the B direction
no second link as the C direction is a dead end
A node corresponding to switch 3:
1 outgoing link to node 6, weight 2, corresponding to taking the C direction
1 outgoing link to node 9, weight 3, corresponding to taking the B direction and passing switches 3, 7 and 8
and so on for every switch. This yield a graph with 10 nodes, each having at most 2 directed edges.
Now we can start building our Dijkstra tree. We start at node 1 and have 2 possible directions, B and C. We put those on a priorityqueue. The queue then contains [node 2,weight 2] and [node 3, weight 2] as we can reach the A entrance of switch 2 after passing 2 switches and the A entrance of switch 3 after passing 2 switches. We then continue the search by taking the lowest weight entry from the queue:
[node 2, weight 2]: only the B direction to take, so put [node 6, weight 4] on the queue
[node 3, weight 2]: 2 directions to take, so add [node 6, weight 4] and [node 9, weight 5] to the queue.
[node 6, weight 4]: 2 directions possible, add [node 4, weight 5] and [node 8, weight 8] to the queue]
[node 9, weight 5]: only the C direction, add [node 10, weight 6]
[node 4, weight 5]: add [node 5, weight 7] for the C direction and [node 1, weight 9] for the B direction]
[node 10, weight 6]:add [node 1, weight 8] for the C direction and [node 1, weight 10] for the B direction
[node 5, weight 7]:add [node 1, weight 11] and [node 8, weight 10]
[node 8, weight 8]: add [node 7, weight 9]
[node 1, weight 8]: we found our way back so we can stop
(mistakes are possible, I'm just doing this by hand)
The algorithm then stops with a final length of 8 for a cycle. Determining the followed path is then just a matter of maintaining parent pointers for the nodes when you settle them and unpack the path.
We can use Dijkstra because each node in H corresponds to traversing an original node (in G) in the right direction. Each node in H can then be settled in a Dijkstra fashion so the complexity of the algorithm is limited to that of Dijkstra (which can handle the 100k upper limit for the number of switches).

m-Reachability in graphs

Suppose you have an NxN maze with a Knight, Princess and Exit.
There is also an evil Witch that is planning to block M squares (set them on fire). She will set all these blocks on fire before the Knight makes his first move (they do not alternate turns).
Given the map to the maze, and M, can you decide in O(N^2) whether the Knight will be able to reach the princess, and then the exit, for any choice of blocks by the Witch (meaning - can the Witch make choices that would prevent the Knight & Princess from escaping)?
This problem seems to be equivalent to determining if there exists M + 1 distinct paths from the knight to the princess, and M + 1 distinct paths from the princess to the exit. If there are only M distinct paths from the knight to the princess (or princess to exit), the witch can just burn one square from each path, blocking the rescue (and, alas, any chance of a happily-ever-after romance between them).
For example, the maze in your question has two distinct paths from the knight to the princess, and two distinct paths from the princess to the exit. Thus, the which can burn min(2, 2) to prevent escape.
The number of distinct paths between two points can be found by using a maximal network flow algorithm. Each cell in the grid is a node in the network; two nodes have an edge (of capacity 1) connecting them if they are adjacent and both white. The maximal network flow from the one point to another represents the number of distinct paths between them.
The Ford Fulkerson algorithm will solve the network flow problem in O(E * f) time, where E is the number of edges in the network (at most N^2) and f is the value of the maximum network flow. Because the maximum network flow is at most 4 (the knight only has four possible directions for his first move), the total complexity becomes O(2 * E * 4) = O(N^2), as requested.
Avoiding using a node more than once
As others have pointed out, the above solution prevents edges going into and out of nodes being used more than once; not the nodes themselves.
We can modify the flow graph to avoid nodes being used more than once by giving each cell four input edges, a single guard edge, and four output edges (each having a weight of 1) as follows:
The output edge of one cell corresponds to the input of another. Each cell can now only be used for one path, as the guard edge can only have a flow of 1. Sink and source cells remain unchanged. We still have a constant number of edges per cell, leaving the complexity of the algorithm unchanged.

Resources