Dfs clean and optimized code