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>
using namespace std;

const int dy[] = { 1, 0, -1, 0}, dx[] = { 0, 1, 0, -1};
bool check[1 << 12];
int H, W, K, dp[50][50][1 << 12];
char Gifts[50][50];

int main(){

  cin >> H >> W >> K;
  const int mask = (1 << (K * 4)) - 1;
  for(int i = 0; i <= mask; ++i){
    bool flag = false;
    int y = 0, x = 0, bit = i;
    for(int j = 0; j < 2 * K; ++j){
      y -= dy[bit & 3], x -= dx[bit & 3];
      if(y == 0 && x == 0){
        flag = true;
        break;
      }
      bit >>= 2;
    }
    check[i] = !flag;
  }

  for(int i = 0; i < H; ++i){
    for(int j = 0; j < W; ++j){
      cin >> Gifts[i][j];
    }
  }
  fill_n( **dp, 50 * 50 * (1 << 12), -1);
  // dp[i][j][S]: ( j, i)にいるときの前に訪れる方法Sにおいての最大値
  dp[0][0][0] = 0;
  for(int i = K; i >= 0; --i){
    for(int j = 0; j < H; ++j){
      for(int k = 0; k < W; ++k){
        for(int l = 0; l <= mask; ++l){
          if(dp[j][k][l] == -1) continue;
          int cost;
          if(isdigit(Gifts[j][k]) && check[l]) cost = Gifts[j][k] - '0';
          else cost = 0;
          for(int m = 0; m < 4; ++m){
            int ny = j + dy[m], nx = k + dx[m];
            if((m > 1 && i == 0) || ny < 0 || ny >= H || nx < 0 || nx >= W || Gifts[ny][nx] == '#') continue;
            int& res = dp[ny][nx][(l << 2 | m) & mask];
            res = max( res, dp[j][k][l] + cost);
          }
        }
      }
    }
  }
  int ret = 0;
  for(int i = 0; i <= mask; ++i){
    ret = max( ret, dp[H - 1][W - 1][i]);
  }
  cout << ret << endl;
}