Problem: problem

JOI, who came to Australia for a trip, enjoyed sightseeing in various places and finally returned to Japan. Now, JOI is in the town with the international airport where the return flight departs. The town is divided into north, south, east and west, and each section has roads, souvenir shops, houses, and an international airport. JOI starts from the northwestern section and heads for the international airport in the southeastern section.

JOI can move from the current parcel to an adjacent parcel, but cannot enter a parcel with a house. Also, move only to the east or south section of the current section in order to make it in time for the flight. However, there is some time to spare, so you can move to the north or west section of the section you are up to K times.

When JOI enters the area where the souvenir shop is located, he buys souvenirs for his Japanese friends. JOI did a lot of research on the souvenir shops, so he knows which souvenir shop to buy and how many souvenirs to buy. Create a program to find the maximum number of souvenirs you can buy.

However, the time to buy souvenirs can be ignored, and if you visit the same souvenir shop more than once, you will only buy souvenirs the first time you visit.





Example

Input

5 4 2
...#
.#.#
.#73
8##.
....


Output

11

Solution (in CPP):

Solution:
#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

int w, h, k;
int memo[1 << 12][4][50][50];
int mask;
int dx[] = {1, 0, -1, 0}, dy[] = {0, 1, 0, -1};
char field[64][64];

bool check(int ny, int nx)
{
	return (0 <= ny && ny < h && 0 <= nx && nx < w);
}

int getMax(int bit, int left, int ty, int tx)
{
	if (memo[bit][left][ty][tx] != -1) return (memo[bit][left][ty][tx]);
	
	if (ty == h - 1 && tx == w - 1 && left == 0){
		return (0);
	}
	
	int px = tx, py = ty;
	bool same = false;
	for (int i = 0; i < 2 * k; i++){
		px += -dx[(bit >> (2 * i)) & 3];
		py += -dy[(bit >> (2 * i)) & 3];
		if (px == tx && py == ty){
			same = true;
			break;
		}
	}
	
	int ret = 0;
	
	if (!same && field[ty][tx] != '.') ret += field[ty][tx] - '0';
	
	int val = -999999;
	for (int i = 0; i < 4; i++){
		if (left == 0 && i >= 2) break;
		int nx = tx + dx[i], ny = ty + dy[i];
		if (check(ny, nx) && field[ny][nx] != '#'){
			val = max(val, getMax(((bit << 2) | i) & mask, left - (i >= 2), ny, nx) + ret);
		}
	}
	
	return (memo[bit][left][ty][tx] = val);
}

int main()
{
	scanf("%d %d %d", &h, &w, &k);
	
	mask = (1 << (4 * k)) - 1;
	
	for (int i = 0; i < h; i++){
		scanf("%s", field[i]);
	}
	
	memset(memo, -1, sizeof(memo));
	
	int res = getMax(0, k, 0, 0);
	
	printf("%d\n", res < 0 ? 0 : res);
	
	return (0);
}