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;
int dp[5][50][50][1 << 12];
int H, W, K;
char mas[50][50];
int dy[] = { 0, 1, 0, -1}, dx[] = { 1, 0, -1, 0};
int mask;
 
int getdir(int bit, int i){
  return bit >> (i << 1) & 3;
}
bool isover(int y, int x){
  return y < 0 || y >= H || x < 0 || x >= W;
}
bool check(int y, int x, int bit){
  if(mas[y][x] == '.') return false;
  for(int i = 0, my = y, mx = x; i < 2 * K; i++){
    my -= dy[getdir( bit, i)], mx -= dx[getdir( bit, i)];
    if(my == y && mx == x) return false;
  }
  return true;
}
int main()
{
  cin >> H >> W >> K;
  mask = (1 << (K * 2 * 2)) - 1;
  for(int i = 0; i < H; i++){
    for(int j = 0; j < W; j++){
      cin >> mas[i][j];
    }
  }
  fill_n( ***dp, 5 * 50 * 50 * 1 << 12, -1);
  dp[K][0][0][0] = 0;

  for(int mul = K ; mul >= 0; mul--){
    for(int y = 0; y < H; y++){
      for(int x = 0; x < W; x++){
        for(int bit = 0; bit < 1 << (K * 4) ; bit++){ // 前の街
          if(dp[mul][y][x][bit] == -1 || mas[y][x] == '#') continue;
          int cost = check( y, x, bit) * (mas[y][x] - '0');
          for(int i = 0; i < 4; i++){
            int ny = y + dy[i], nx = x + dx[i];
            if(isover(ny,nx) || mas[ny][nx] == '#') continue;
            if(mul == 0 && i >= 2) break;
            int& next = dp[mul - (i > 1)][ny][nx][(bit << 2 | i) & mask];
            next = max( next, dp[mul][y][x][bit] + cost);
          }
        }
      }
    }
  }
  cout << *max_element(dp[0][H-1][W-1],dp[0][H-1][W]) << endl;
  return 0;
}