revised the graph search with memoization for calculations