Skip to main content
1 of 2
John L.
  • 39.1k
  • 4
  • 34
  • 91

Your algorithm works. The main concept here are tree and cycle.

it is possible iff no cycles or one cycle

Claim: Let $G$ be an undirected connected graph. $G$ can be turned into a directed graph with in-degree at most $1$ iff $G$ has no cycles or exactly one cycle.
Proof: "$\Leftarrow$":
If $G$ has no cycle, it is a tree. Pick any node as the root, it is easy to change an undirected tree into a directed rooted tree.

If $G$ has one cycle, change that cycle into a directed cycle. Contract this cycle into one vertex so that $G$ becomes an undirected tree. Using that vertex as the root, change $G$ into a directed rooted tree. We have, in fact, assigned a direction for each edge in the original $G$ so that it becomes a directed graph with in-degree at most $1$.

"$\Rightarrow$":
Suppose $G$ is turned into directed graph $G'$ with in-degree at most $1$.

Consider $G'$. Since different edges must have different tails, the number of edges is no more than the number of nodes.

Since $G$ and $G'$ have the same number of edges and the same number of nodes, the number of edges in $G$ is no more than the number of nodes in $G$. As a connected graph, $G$ has at least $|V|-1$ edges.

  • $G$ has $|V|-1$ edges.
    Then $G$ must be a tree, which has no cycles.
  • Otherwise $G$ has $|V|$ edges.
    Let $T$ be a spanning tree of $G$, which has $|V|-1$ edges. $G$ is $T$ plus one edge. So $G$ has exactly one cycle.

Your algorithm works

It is enough to show your algorithm works on each connected component.

Assume the given graph, $G$ is connected.

If $G$ has more than one cycle, then it is impossible to change $G$ as wanted. Your algorithm must return "impossible" as well.

If $G$ has no cycle, your algorithm will pick a leaf every time. In the end, your algorithm will produce a directed rooted tree.

If $G$ has one cycle, your algorithm will pick a leaf every time until all remaining nodes has more than one incidental edge. Then, in fact, all remaining nodes form a cycle. Your algorithm will assign a direction to one of its edge. Then spread the direction either way one edge at a time. In the end, every node will have in-degree $1$.

Another algorithm

Split $G$ into connected components.

For each connected component $C$, check the number of edges in it.

  • If the number of edges is one more than the number of nodes, return "impossible".
  • If the number of edges is less than the number of nodes, $C$ is a tree. Pick any node as the root. Make $C$ a directed rooted tree.
  • Otherwise, there is a unique cycle in $C$. Find that cycle. Change that cycle into a directed cycle. Imagine the nodes in the cycle as one (super-)node. Picking that node as root, make $C$ a directed root tree.
John L.
  • 39.1k
  • 4
  • 34
  • 91