Nice problem. Using stack instead of DFS.