All problems

Problem 631

Shortest Path in a Grid with Obstacles Elimination

Hard · 30 pts · Matrix, Breadth-First Search

Problem

A grid has empty cells (0) and obstacles (1). You start at the top-left cell and want to reach the bottom-right cell, moving one step up, down, left or right at a time. You may walk through at most K obstacles on the way. Find the minimum number of steps, or -1 if it is impossible. Both corner cells are empty. Run a breadth-first search over states (row, column, obstacles still allowed), visiting each state once.

Input

The first line contains R, C and K. Each of the next R lines is a row of C characters 0 or 1.

Output

Print the minimum number of steps, or -1.

Constraints

1 <= R, C <= 40; 0 <= K <= R × C; the top-left and bottom-right cells are 0

Example input

5 3 1
000
110
000
011
000

Example output

6

Explanation

In the grid 000 / 110 / 000 / 011 / 000 with K = 1, go right along the top row to (0,2), then straight down the last column to (4,2), passing through the obstacle at (3,2). That takes 6 steps, while avoiding every obstacle would take 10.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Regions Cut By Slashes Next: Count Unreachable Pairs of Nodes