From Algorithm Wiki
- Create a directed graph with the vertices representing the children and the edges representing the "i hates j" relations and use topological sorting. This will either give out a list representing the order in the line or tell you if it's not possible, i.e. a cycle is in the graph.
- Build a BFS graph from the directecd graph as built in the previous task. The maximum depth of this graph is the number of rows necessary.