This page is still under construction.

Parts of this page are still being built. What you see may change.

Siru's Department Store Tour

Time limit2sMemory limit1024 MB

Summary
Find the shortest path on a grid from Siru's start to any chair, avoiding pillars and cells within Manhattan distance K of mannequins.
Level

Medium5 of 10

Topics
BFS, Matrix, Shortest path
Solved
No attempts yet

Problem

Siru went to a department store with her parents. Her parents have a lot of shopping to do and need to visit many places. Walking around with them is too tiring for Siru, so she wants to sit down on a chair and rest.

The department store is a grid with NN rows and MM columns. Each move to an adjacent cell up, down, left, or right costs 1 stamina. Siru starts at her current position and wants to walk to one of the chairs scattered around the store and sit down. Siru cannot leave the department store, because her parents would scold her.

The store has pillars that hold up the building and mannequins that display clothes. Siru cannot move into a cell with a pillar. She is afraid of mannequins, so she also avoids every cell whose distance to a mannequin is KK or less. The distance between cells (rx,cx)(r_x, c_x) and (ry,cy)(r_y, c_y) is ∣rx−ry∣+∣cx−cy∣\vert r_x-r_y \vert + \vert c_x-c_y \vert. However, Siru sets out with her parents, so she can leave even if her starting cell is within distance KK of a mannequin.

Her legs hurt, so she wants to reach a chair while spending as little stamina as possible. Find the minimum stamina Siru spends.

Input

The first line contains the number of rows NN, the number of columns MM, and the distance KK that must be kept from mannequins, separated by spaces. (1≤N,M≤2 0001 \leq N,M \leq 2\,000, 0≤K≤4 0000 \leq K \leq 4\,000)

The next NN lines each contain MM numbers, describing the store from top to bottom. An empty cell is 0, a pillar is 1, a chair is 2, a mannequin is 3, and Siru's starting position is 4. The starting position appears exactly once, and it holds no pillar, chair, or mannequin.

Output

If Siru can reach a chair, print the minimum stamina she spends. If she cannot reach any chair, print -1.

Hint

Python users are recommended to submit with PyPy.

Examples4

  1. Example 1

    Input
    5 5 1
    0 0 0 0 4
    0 0 0 1 0
    0 0 0 0 3
    0 0 0 1 0
    0 0 0 0 2
    
    Expected output
    8
    
  2. Example 2

    Input
    5 5 2
    0 0 0 0 4
    0 0 0 1 0
    0 0 0 0 3
    0 0 0 1 0
    0 0 0 0 2
    
    Expected output
    -1
    
  3. Example 3

    Input
    5 5 2
    2 0 0 0 4
    0 0 0 1 0
    0 0 0 0 3
    0 0 0 1 0
    0 0 0 0 0
    
    Expected output
    4
    
  4. Example 4

    Input
    5 5 0
    0 0 0 0 4
    0 0 0 1 0
    0 0 0 0 3
    0 0 0 1 0
    0 0 0 0 0
    
    Expected output
    -1