Write a function to find the shortest path in a dynamic network grid, optimizing for both space and time complexity.