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<bits/stdc++.h>

#define REP(i,s,n) for(int i=s;i<n;i++)
#define rep(i,n) REP(i,0,n)

using namespace std;

const int IINF = INT_MAX;
int h,w,K;
char c[51][51];
int memo[50][50][1<<12][4];
int dx[] = {0,1,0,-1}; // ????????????
int dy[] = {1,0,-1,0};

inline bool isValid(int x,int y) { return 0 <= x && x < w && 0 <= y && y < h; }

int dfs(int x,int y,int remain,int bit){

  if( memo[y][x][bit][remain] != -1 ) return memo[y][x][bit][remain];
  
  if( x == w-1 && y == h-1 && remain == 0 ) return 0;
  
  int px = x,py = y;
  bool already_visited = false;
  rep(i,(2*K)){
    px -= dx[(bit>>(i*2))&3];
    py -= dy[(bit>>(i*2))&3];
    if( !isValid(px,py) ) break;
    if( px == x && py == y ) {
      already_visited = true;
      break;
    }
  }

  int ret = 0;
  if( !already_visited && '0' <= c[y][x] && c[y][x] <= '9' ) ret = c[y][x] - '0';
  
  int maxi = -2;
  rep(i,4){
    int nx = x + dx[i], ny = y + dy[i];
    if( !isValid(nx,ny)  ) continue;
    if( c[ny][nx] == '#' ) continue;
    if( i >= 2 && remain == 0 ) continue;
    maxi = max(maxi,dfs(nx,ny,remain-(i>=2),((bit<<2)|i)&((1<<(4*K))-1)));
  }

  if( maxi == -2 ) return memo[y][x][bit][remain] = -2;
  return memo[y][x][bit][remain] = ret + maxi;
  
}

int main(){
  scanf("%d %d %d",&h,&w,&K);
  rep(i,h) scanf(" %s",&c[i][0]);
  memset(memo,-1,sizeof(memo));
  int tmp = dfs(0,0,K,2);
  if( tmp == -2 ) puts("0");
  else            printf("%d\n",dfs(0,0,K,0));
  return 0;
}