#include #include #include #include #include #include using namespace std; using namespace atcoder; using ll = long long; using mint = modint998244353; using vi = vector; using vvi = vector; using vvvi = vector; using vll = vector; using vvll = vector; using vvvll = vector; using vmi = vector; using vvmi = vector; using vvvmi = vector; #define all(a) (a).begin(), (a).end() #define rep2(i, m, n) for (int i = (m); i < (n); ++i) #define rep(i, n) rep2(i, 0, n) #define drep2(i, m, n) for (int i = (m)-1; i >= (n); --i) #define drep(i, n) drep2(i, n, 0) using p = pair; int inf = 2e9+7; int main(){ int h, w, n; cin >> h >> w >> n; vector

vst(n), vg(n); rep(i, n){ int a, b, c, d; cin >> a >> b >> c >> d; vst[i] = {a, b}; vg[i] = {c, d}; } vvi dist(2*n+2, vi(2*n+2, inf)); p goal = {h, w}; rep(i, n){ auto [c, d] = vg[i]; dist[i][i+n] = 1; dist[i+n][2*n+1] = h+w-c-d; rep(j, n){ auto [a, b] = vst[j]; dist[i+n][j] = abs(c-a) + abs(d-b); } } rep(i, n){ auto [a, b] = vst[i]; dist[2*n][i] = a+b-2; dist[i][2*n+1] = h+w-a-b; } dist[2*n][2*n+1] = h+w-2; vvi adj(2*n+2); rep(i, 2*n+2){ rep(j, 2*n+2){ if(dist[i][j] < inf)adj[i].push_back(j); } } vi ans(2*n+2, inf); ans[2*n] = 0; priority_queue, greater

> pq; pq.push({0, 2*n}); while(!pq.empty()){ p u = pq.top(); pq.pop(); if(u.first > ans[u.second])continue; for(auto v : adj[u.second]){ int alt = u.first + dist[u.second][v]; if(alt < ans[v]){ ans[v] = alt; pq.push({alt, v}); } } } cout << ans[2*n+1] << endl; return 0; }