#include <iostream>
#include <vector>
#include <array>
#include <cmath>
#include <string>
#include <algorithm>
#include <functional>
#include <map>
#include <tuple>
#include <queue>
#include <bitset>
#define rep(i,n) for(int i = 0;i < (n);i++)
using namespace std;
using ll = long long int;
int cnt = 0; 
using Graph = vector<vector<int>>;

vector<bool> seen;  // 探索したか記録
void dfs(const Graph &G, int v) {
    seen[v] = true;
    for (auto e : G[v]) {
        if (seen[e]) continue;  // 訪問済みでなければ探索
    
        dfs(G, e);
        
    }
    cnt++;
}

int main(){
    int n,m;cin>>n>>m;
    Graph G(n);
    rep(i,m){
        int a,b;cin>>a>>b;
        a--;b--;
        G[a].push_back(b);
    }
      // 初期化
    
    rep(i,n) {
        seen.assign(n, false);
        if (!seen[i]) {
            dfs(G, i);
        
        }
    }
    cout << cnt << endl;
    return 0;
}
//#include <atcoder/all>
//using namespace atcoder;
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define REP(i, n) for(int i=0; i<n; i++)
#define REPR(i, n) for(int i=n-1; i>=0; i--)
#define FOR(i, m, n) for(int i=m; i<n; i++)
#define ALL(v) v.begin(), v.end()
#define bit(n) (1LL<<(n))
#define FIX(d) fixed << setprecision(d)
using P = pair<int, int>;
using LP = pair<ll, ll>;
using vvi = vector<vector<int>>;
using vvl = vector<vector<ll>>;
template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; }
template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; }
const int INF = 1e9;
const ll LINF = (1LL<<60);

struct edge
{
  int to;
  int cost;
  
  edge(int a, int b){
    to = a;
    cost = b;
  }  
};
using Graph = vector<vector<edge>>;

vector<ll> dijkstra(int s, const Graph &G)
{
  int n = G.size();
  priority_queue<P, vector<P>, greater<P>> que;
  vector<ll> d(n, INF);
  d[s] = 0;
  que.emplace(0, s);

  while (!que.empty()){
    P p = que.top();
    que.pop();
    int v = p.second;
    if (d[v] < p.first) continue;

    for(auto nv: G[v]){
      if (d[nv.to] > d[v] + nv.cost){
        d[nv.to] = d[v] + nv.cost;
        que.emplace(d[nv.to], nv.to);
      }
    }
  }
  return d;
}

int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);
  int r,c; cin >> r >> c;
  vvi a(r, vector<int>(c-1)), b(r-1, vector<int>(c));
  REP(i,r) REP(j,c-1) cin >> a[i][j];
  REP(i,r-1) REP(j,c) cin >> b[i][j];

  Graph G(r*c);
  REP(i,r) REP(j,c){
    // r,c -> r,c+1
    if(j<c-1) G[i*c+j].push_back(edge(i*c+(j+1), a[i][j]));

    // r,c -> r,c-1
    if(j>0) G[i*c+j].push_back(edge(i*c+(j-1), a[i][j-1]));

    // r,c -> r+1,c
    if(i<r-1) G[i*c+j].push_back(edge((i+1)*c+j, b[i][j]));

    // r,c -> r-k,c 
    REP(k,i) G[i*c+j].push_back(edge((i-k-1)*c+j, k+2));
  }
  
  auto dist = dijkstra(0, G);
  cout << dist[r*c-1] << endl;
  return 0;
}
