1 #include<iostream>
2 #include<cstdio>
3 #include<cstdlib>
4 #include<cstring>
5 #include<queue>
6 #define Max 2147483640
7 #define dis first
8 #define pos second
9 #define mk(A,B) make_pair(A,B)
10 #define d(A,B,C) ((A-1)*m*2+m*(C-1)+B)
11 using namespace std;
12 typedef pair<int,int> nod;
13 int read()
14 {
15 char ch=getchar();int cn=0,kin=1;
16 while(ch>‘9‘||ch<‘0‘){if(ch==‘-‘)kin=-1;ch=getchar();}
17 while(ch>=‘0‘&&ch<=‘9‘){cn=cn*10+ch-48;ch=getchar();}
18 return cn*kin;
19 }
20 struct ni
21 {
22 vector<int>s[2];
23 int ml;
24 }a[2000005];
25 int n,m,t;
26 priority_queue<nod,vector<nod>,greater<nod> >que;
27 void get(int,int);
28 void init();
29 int main()
30 {
31 freopen("a.in","r",stdin);
32 n=read()-1;m=read()-1;
33 if(n==0||m==0)
34 {
35
36 if(n<m)swap(n,m);
37 int la,ans=Max;
38 for(int i=1;i<=n;++i)
39 {
40 la=read();
41 ans=min(ans,la);
42 }
43 cout<<ans<<endl;return 0;
44 }
45 t=n*2*m+1;
46 init();que.push(mk(0,0));
47 int nw,d;
48 while(!que.empty())
49 {
50 nw=que.top().second;d=que.top().first;que.pop();
51 for(int i=0;i<a[nw].s[0].size();++i)
52 {
53 if(d+a[nw].s[1][i]<a[a[nw].s[0][i]].ml)
54 {
55 a[a[nw].s[0][i]].ml=d+a[nw].s[1][i];
56 que.push(mk(a[a[nw].s[0][i]].ml,a[nw].s[0][i]));
57 }
58 }
59 }
60 cout<<a[t].ml<<endl;
61 fclose(stdin);
62 return 0;
63 }
64 void get(int x,int y)
65 {
66 int t1;
67 t1=read();
68 a[x].s[0].push_back(y);
69 a[x].s[1].push_back(t1);
70 a[y].s[0].push_back(x);
71 a[y].s[1].push_back(t1);
72 }
73 void init()
74 {
75 for(int i=1;i<=n*2*m;++i)
76 {
77 a[i].ml=Max;
78 }a[t].ml=Max;
79 for(int i=1;i<=n+1;++i)
80 for(int j=1;j<=m;++j)
81 {
82 if(i==1)
83 get(d(i,j,1),t);
84 else if(i==n+1)
85 get(0,d(i-1,j,2));
86 else
87 get(d(i,j,1),d(i-1,j,2));
88 }
89 for(int i=1;i<=n;++i)
90 for(int j=1;j<=m+1;++j)
91 {
92 if(j==1)
93 get(d(i,j,2),0);
94 else if(j==m+1)
95 get(d(i,j-1,1),t);
96 else
97 get(d(i,j,2),d(i,j-1,1));
98 }
99 for(int i=1;i<=n;++i)
100 for(int j=1;j<=m;++j)
101 {
102 get(d(i,j,1),d(i,j,2));
103 }
104 }