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 <cstdio>
#include <queue>
#include <algorithm>
#include <map>
#include <tuple>
#include <set>

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

using namespace std;

typedef pair<int, int> P;
typedef tuple<P, int, set<P>> T;

int n, m, z;
char x[50][51];

int a;
map<T, int> b;

int main(){
	scanf("%d%d%d", &n, &m, &z);
	rep(i, n){
		scanf("%s", x[i]);
	}

	queue<T> q;
	q.push(T(P(0, 0), z, {}));
	while(!q.empty()){
		T t = q.front();
		q.pop();
		P p = get<0>(t);
		int z = get<1>(t);
		set<P> s = get<2>(t);
		if(p == P(n - 1, m - 1)){
			a = max(b[T(p, z, s)], a);
		}

		int dx[] = {0, 1, 0, -1};
		int dy[] = {1, 0, -1, 0};
		rep(i, 4){
			int nx = p.first + dx[i];
			int ny = p.second + dy[i];
			int nz = i >= 2 ? z - 1 : z;

			if(!(0 <= nx && nx < n && 0 <= ny && ny < m && nz >= 0 && x[nx][ny] != '#')){
				continue;
			}

			int g = 0;
			set<P> ns;
			if('1' <= x[nx][ny] && x[nx][ny] <= '9' && s.find({nx, ny}) == s.end()){
				ns.insert({nx, ny});
				g = x[nx][ny] - '0';
			}
			for(auto it = s.begin(); it != s.end(); ++it){
				int u = max(nx - it->first, 0);
				int v = max(ny - it->second, 0);
				if(u + v <= nz){
					ns.insert(*it);
				}
			}

			T nk({nx, ny}, nz, ns);
			if(b.find(nk) == b.end() || b[nk] < b[T(p, z, s)] + g){
				b[nk] = b[T(p, z, s)] + g;
				q.push(T({nx, ny}, nz, ns));
			}
		}
	}
	printf("%d\n", a);
	return 0;
}