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,n) for(int i=0;i<(int)(n);i++)
#define range(x,l,r) (l<=x && x<r)
#define chmax(a,b) (a = max(a,b))
using namespace std;

const int dy[] = {0,1,0,-1}, dx[] = {1,0,-1,0};
int dp[2][50][50][1<<12];
int vis[1<<12];

inline int visit(int bit){
  if(vis[bit]>=0)return vis[bit];

  int y=0, x=0, b=bit;
  rep(i,6){
    y += dy[b&3], x += dx[b&3]; b>>=2;
    if(y==0 && x==0)return vis[bit] = 1;
  }
  return vis[bit] = 0;
}

int main(){
  cin.tie(0); ios::sync_with_stdio(0);
  int h,w,k;
  string g[50];
  cin >> h >> w >> k;
  rep(i,h)cin >> g[i];

  memset(vis,-1,sizeof(vis));
  memset(dp,-1,sizeof(dp));
  dp[0][0][0][0] = isdigit(g[0][0])?(int)(g[0][0]-'0'):0;

  rep(t,k+1){
    int ck = t&1, nk = 1-ck;
    rep(y,h)rep(x,w){
      if(g[y][x] == '#')continue;
      rep(bit,1<<12){
	if(dp[ck][y][x][bit]<0)continue;

	rep(d,4){
	  if(t==k && d>1)break;
	  int ny = y+dy[d], nx = x+dx[d];
	  if(!range(ny,0,h) || !range(nx,0,w))continue;
	  if(g[ny][nx] == '#')continue;

	  int nbit = ((bit<<2)|d) & ((1<<12)-1);
	  int item = isdigit(g[ny][nx])?(int)(g[ny][nx]-'0'):0;
	  if(visit(nbit))item = 0;

	  if(d<2){
	    chmax(dp[ck][ny][nx][nbit], dp[ck][y][x][bit] + item);
	  }else{
	    chmax(dp[nk][ny][nx][nbit], dp[ck][y][x][bit] + item);
	  }
	}
      }
    }
  }

  int res = 0;
  rep(bit,1<<12)chmax(res, dp[k&1][h-1][w-1][bit]);
  cout << res << endl;
}