uva1600

maksyuki 发表于 oj 分类,标签:
0

A robot has to patrol around a rectangular area which is in a form of m x n grid (m rows and n columns). The rows are labeled from 1 to m. The columns are labeled from 1 to n. A cell (ij) denotes the cell in row iand column j in the grid. At each step, the robot can only move from one cell to an adjacent cell, i.e. from(xy) to (x + 1, y), (xy + 1), (x - 1, y) or (xy - 1). Some of the cells in the grid contain obstacles. In order to move to a cell containing obstacle, the robot has to switch to turbo mode. Therefore, the robot cannot move continuously to more than k cells containing obstacles.

Your task is to write a program to find the shortest path (with the minimum number of cells) from cell (1, 1) to cell (mn). It is assumed that both these cells do not contain obstacles.

Input

The input consists of several data sets. The first line of the input file contains the number of data sets which is a positive integer and is not bigger than 20. The following lines describe the data sets.

For each data set, the first line contains two positive integer numbers m and n separated by space (1mn20). The second line contains an integer number k (0k20). The ith line of the next m lines contains ninteger aij separated by space (i = 1, 2,..., m;j = 1, 2,..., n). The value of aij is 1 if there is an obstacle on the cell (ij), and is 0 otherwise.

Output

For each data set, if there exists a way for the robot to reach the cell (mn), write in one line the integer number s, which is the number of moves the robot has to make; -1 otherwise.

Sample Input

3 2 5 0 0 1 0 0 0 0 0 0 1 0 4 6 1 0 1 1 0 0 00 0 1 0 1 10 1 1 1 1 00 1 1 1 0 02 2 0 0 1 1 0

Sample Output

7 10 -1

 

题目类型:BFS

算法分析:使用visited[i][j][v]数组表示走到(i, j)且已经通v个墙的状态是否已经访问过。对于走到的节点值为1且还能够向下一个状态走,则将该状态的能力值减1,步数加1;如果走到的节点值为0,则将能力值恢复为k(只有这样才能最大化能力值,求得最短步数),步数加1。一直这样扩展节点,直到有一个状态的坐标为(X, Y),最后输出该状态的步数