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;
inline void ChMax(int& a, int b){ a = max(a, b); }

const int dy[] = {-1, 0, 0, 1}, dx[] = {0, -1, 1, 0};
const int bitMask = (1 << 12) - 1;
int H, W, K;
char S[50][50];
int dp[50][50][1 << 12];
bool Visited[1 << 12];



int main()
{
  memset(dp, -1, sizeof(dp));
  for (int i = 0; i < (1 << 12); i++) {
    int nx = 0, ny = 0, bit = i;
    for(int j = 0; j < 6; j++, bit >>= 2) {
      nx -= dx[bit & 3], ny -= dy[bit & 3];
      if (nx == 0 && ny == 0) Visited[i] = true;
    }
  }

  cin >> H >> W >> K;
  for (int i = 0; i < H; i++) {
    for (int j = 0; j < W; j++) {
      cin >> S[i][j];
    }
  }

  dp[0][0][bitMask] = 0;

  for(int m = K; m >= 0; m--) {
    int notnext = m == 0;
    for (int i = 0; i < H; i++) {
      for (int j = 0; j < W; j++) {
        for (int k = 0; k < (1 << 12); k++) {
          if (dp[i][j][k] == -1) continue;
          int Get = 0;
          if (isdigit(S[i][j]) && !Visited[k]) Get += S[i][j] - '0';
          for (int l = notnext << 1; l < 4; l++) {
            int ny = i + dy[l], nx = j + dx[l];
            if (ny < 0 || nx < 0 || ny >= H || nx >= W) continue;
            if (S[ny][nx] == '#')                       continue;
            ChMax(dp[ny][nx][((k << 2) | l) & bitMask], dp[i][j][k] + Get);
          }
        }
      }
    }
  }
  cout << *max_element(dp[H - 1][W - 1], dp[H - 1][W]) << endl;
}