traversing different paths to find the most efficient solution, code is a bit messy