Implement an algorithm to find the shortest path in a network grid, optimizing for both time and space complexity.