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<algorithm>
#include<iostream>
#include<cstring>

const int INF = 1 << 30;

int W, H, K;
// 00 → 右 01 → 下 10 → 左 11 → 上
int memo[1 << 12][4][50][50];
int dx[] = { 1, 0, -1, 0 }, dy[] = { 0, 1, 0, -1 };
char field[50][50];
int mask;

int rec( int bit, int k, int y, int x )
{
	if( memo[bit][k][y][x] != -1 )
		return memo[bit][k][y][x];

	if( y == H - 1 && x == W - 1 && !k )
		return 0;

	int tx = x, ty = y;
	bool f = false;
	for( int i = 0; i != 2 * K; ++i )
	{
		tx -= dx[( bit >> ( 2 * i ) ) & 3];
		ty -= dy[( bit >> ( 2 * i ) ) & 3];

		if( tx == x && ty == y )
		{
			f = true;
			break;
		}
	}

	int ret = 0;
	
	if( !f && field[y][x] >= '0' && field[y][x] <= '9' )
		ret += field[y][x] - '0';

	int ans = -INF;

	for( int i = 0; i != 4; ++i )
	{
		if( !k && i >= 2 )
			break;

		int nx = x + dx[i], ny = y + dy[i];
		if( nx >= 0 && nx < W && ny >= 0 && ny < H && field[ny][nx] != '#' )
			ans = std::max( ans, rec( ( ( bit << 2 ) | i ) & mask, k - ( i >= 2 ), ny, nx ) + ret ); 
	}

	return memo[bit][k][y][x] = ans;
}

int main()
{
	std::cin >> H >> W >> K;

	mask = ( 1 << ( 4 * K ) ) - 1;

	for( int i = 0; i != H; ++i )
		for( int j = 0; j != W; ++j )
			std::cin >> field[i][j];

	memset( memo, -1, sizeof( memo ) );
	int ans = rec( 0, K, 0, 0 );
	std::cout << ( ans < 0 ? 0 : ans ) << std::endl;

	return 0;
}