#include #include using namespace atcoder; using namespace std; using ll = long long; struct Edge { int to; ll cost; }; using Graph = vector>; ll INF = (1LL << 60); void DJK(int s, vector& dist, Graph& G) { dist[s] = 0; priority_queue, vector>, greater>> pq; int N = G.size(); for (int v = 0;v < N;v++) pq.emplace(dist[v], v); while (!pq.empty()) { int v = pq.top().second;ll dis = pq.top().first;pq.pop(); if (dist[v] < dis) continue; for (auto nv : G[v]) { ll cost = nv.cost + dis; if (cost < dist[nv.to]) { dist[nv.to] = cost; pq.emplace(dist[nv.to], nv.to); } } } } int main() { ll H, W;int N;cin >> H >> W >> N; int K = (2 * N) + 2; vector> pos; pos.push_back({1, 1}); pos.push_back({H, W}); Graph G(K); for (int i = 0;i < N;i++) { ll a, b, c,d;cin >> a >> b >> c >> d; pos.push_back({a,b}); int x = pos.size() - 1; pos.push_back({c, d}); int y = pos.size() - 1; G[x].push_back({y, 1}); } for (int i = 0;i < K;i++) for (int j = 0;j < K;j++) { if (i == j) continue; ll dist = abs(pos[i].first - pos[j].first) + abs(pos[i].second - pos[j].second); G[i].push_back({j, dist}); } vector dist(K, INF); DJK(0, dist, G); cout << dist[1] << endl; }