Reduced lines in grid solver code by looping through directions