Problem: problem

The city of IOI, where JOI lives, has a rectangular shape with H sections in the north-south direction and W sections in the east-west direction, and is divided into H x W sections. The i-th section from the north and the j-th section from the west are represented as (i, j). A large-scale festival is currently being held to commemorate the international programming contest held in IOI City. There are food stalls in some areas, each selling different types of sweets. There are no food stalls in plots (1, 1), plots (H, W) and the plots adjacent to them north, south, east and west.

JOI moves from compartment (1, 1) to compartment (H, W). To shorten the travel time, JOI travels only to the east or south. JOI likes sweets, so he takes the following actions in order each time he enters a section.

1. If there is a stall selling sweets that you have not bought yet in the current section, buy sweets at that stall.
2. If there are food stalls selling sweets that you have not bought yet in the area adjacent to the north, south, east, and west of the current area, call a salesperson from all the stalls except one of those stalls. Buy sweets.



JOI never buys the same kind of sweets more than once.

Given the size of the IOI city, the location of the stalls, and the price of the sweets at each stall, the sweets that JOI buys while moving from parcel (1, 1) to parcel (H, W). Find the minimum value of the total amount of.





Example

Input

5 5
..483
.59.9
3.866
79...
4.8..


Output

20

Solution (in CPP):

Solution:
#include<iostream>
#include<algorithm>
#include<climits>
using namespace std;

int h,w;
int store[1000][1000];
int memo[1000][1000][32];

int getCost(int y,int x){
	if(y<0 || h<=y) return 0;
	if(x<0 || w<=x) return 0;
	return store[y][x];
}

int solve(int y,int x,int bought){
	if(h<=y || w<=x) return INT_MAX;
	if(memo[y][x][bought]!=-1) return memo[y][x][bought];
	
	int ans=INT_MAX;
	int cost;
	int nexte,nexts;

	for(int i=0;i<4;i++){
			cost=0;nexte=0;nexts=0;
			if(bought & 1){
				nexte|=4;nexts|=2;
			}else{
				cost+=getCost(y,x);
			}
			if(i!=0 && !(bought & 2)){
				cost+=getCost(y-1,x);
			}
			if(i!=1 && !(bought & 4)){
				cost+=getCost(y,x-1);
			}
			if(i!=2){
				cost+=getCost(y+1,x);
				nexte|=16;nexts|=1;
			}
			if(i!=3){
				cost+=getCost(y,x+1);
				nexte|=1;nexts|=8;
			}
			if(bought & 8){nexte|=2;}
			if(bought & 16){nexts|=4;}

			if(y!=h-1 || x!=w-1){
				cost+=min(solve(y,x+1,nexte),solve(y+1,x,nexts));
			}
			ans=min(ans,cost);
	}

	memo[y][x][bought]=ans;
	return ans;
}

int main(){
	char c;

	cin>>h>>w;
	for(int y=0;y<h;y++){
		for(int x=0;x<w;x++){
			cin>>c;
			if(c=='.'){
				store[y][x]=0;
			}else{
				store[y][x]=c-'0';
			}
			for(int i=0;i<32;i++){
				memo[y][x][i]=-1;
			}
		}
	}

	cout<<solve(0,0,0)<<endl;
	return 0;
}