Break Walls and Move 2
InterviewTime limit2sMemory limit512 MB
Find the shortest path length from the top-left to the bottom-right of an N by M grid, where you may break at most K walls along the way.
- Level
Medium6 of 10
- Topics
- BFS, Graph, Shortest path, Array
- Solved
- No attempts yet
Problem
A map is given as an matrix. In the map, 0 is a cell you can move into, and 1 is a cell with a wall that you cannot move into. You want to move from to along a shortest path. A shortest path is a path that passes through the fewest cells of the map, counting both the starting cell and the ending cell.
If breaking walls along the way makes the path shorter, you may break up to walls while moving.
From a cell you can move to the cells adjacent to it up, down, left, or right.
Given the map, write a program that finds the length of a shortest path.
Input
The first line contains (), (), and (). Each of the next lines contains one row of the map as digits with no spaces. and are always 0.
Output
Print the length of a shortest path on the first line. If cannot be reached, print -1.