1

From Jeff Erickson's lecture notes on graph algorithms, there is an exercise to check whether a walk between given vertexes s and t can be divisible by 3 in a directed graph.

What I thought is to use breadth-first search on the graph to get all paths from s to t. If the simple paths don't have lengths divisible by 3, run the algorithm again to check if there is a cycle between s and t where the length of cycle is not divisible by 3. However, I feel the method is really inefficient.

It would be great if you have any good suggestion about this question.

kaya3
  • 47,440
  • 4
  • 68
  • 97

1 Answers1

7

This kind of question can often be solved by changing the graph and applying a standard algorithm, instead of changing an algorithm.

In this case, we can create a new graph with three copies of each node, so e.g. if u is a node in the original graph, then the new graph has three corresponding nodes (u, 0), (u, 1) and (u, 2). For each edge u → v in the original graph, the new graph has three corresponding edges (u, 0) → (v, 1), (u, 1) → (v, 2), and (u, 2) → (v, 0).

Given a walk (n_0, r_0) → ... → (n_k, r_k) with k edges, we know that r[i+1] = r[i] + 1 (modulo 3), because all edges in the new graph satisfy that property. Therefore if r_0 = 0 then r_k = k (modulo 3).

It follows that (s, 0) has a walk to (t, 0) in the new graph if and only if s has a walk to t in the original graph using a multiple of 3 edges. So you can just apply a standard path-finding algorithm like BFS in the new graph to see if (t, 0) is reachable from (s, 0).

Note that if you have to actually implement this as code, it is not necessary to actually build the new graph as a data structure; it is an implicit graph.

kaya3
  • 47,440
  • 4
  • 68
  • 97