I used a full topological sort to determine the right order rather than just doing the next permissible operation.