1 #include<algorithm>
2 #include<iostream>
3 #include<cstring>
4 #include<cstdio>
5 #include<cmath>
6 #include<vector>
7 #include<queue>
8 #define N 507
9 using namespace std;
10
11 int n;
12 int mp[N][N][4];
13 int dis[N][N];
14
15 struct dist
16 {
17 int x,y,dis;
18 bool operator < (const dist b) const
19 {
20 return dis>b.dis;
21 }
22 };
23 priority_queue<dist>q;
24 int ans=1e9+7;
25 void insert(int x,int y,int d)
26 {
27 if(d<dis[x][y])
28 {
29 dis[x][y]=d;
30 q.push((dist){x,y,d});
31 }
32 if(y==1)ans=min(ans,d+mp[x][y][1]);
33 if(x==n)ans=min(ans,d+mp[x+1][y][0]);
34 }
35 void Dij()
36 {
37 int i,j;
38 for(i=1;i<=n;i++)
39 insert(1,i,mp[1][i][0]);
40 for(j=1;j<=n;j++)
41 insert(j,n,mp[j][n+1][1]);
42 while(!q.empty())
43 {
44 dist now=q.top();q.pop();
45 if(now.dis>dis[now.x][now.y])continue;
46 int x=now.x,y=now.y;
47 if(x>1) insert(x-1,y,now.dis+mp[now.x][now.y][2]);
48 if(y>1) insert(x,y-1,now.dis+mp[now.x][now.y][1]);
49 if(x<n) insert(x+1,y,now.dis+mp[now.x+1][now.y][0]);
50 if(y<n) insert(x,y+1,now.dis+mp[now.x][now.y+1][3]);
51 }
52 }
53 int main()
54 {
55 scanf("%d",&n);
56 for(int i=1;i<=n+1;i++)
57 for(int j=1;j<=n;j++)
58 scanf("%d",&mp[i][j][0]);//从西到东
59 for(int i=1;i<=n;i++)
60 for(int j=1;j<=n+1;j++)
61 scanf("%d",&mp[i][j][1]);//从北到南
62 for(int i=1;i<=n+1;i++)
63 for(int j=1;j<=n;j++)
64 scanf("%d",&mp[i][j][2]);//从东到西
65 for(int i=1;i<=n;i++)
66 for(int j=1;j<=n+1;j++)
67 scanf("%d",&mp[i][j][3]);//从南到北
68 memset(dis,0x3f,sizeof dis);
69 Dij();
70 cout<<ans<<endl;
71 }