#include using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); long long H,W; cin >> H >> W; int N; cin >> N; vector> edge(N); vector> XY = {{0,0},{H-1,W-1}}; for(auto &[a,b,c,d] : edge){ cin >> a >> b >> c >> d,a--,b--,c--,d--; XY.push_back({a,b}),XY.push_back({c,d}); } sort(XY.begin(),XY.end()); int n = XY.size(); vector dist(n,1e18); dist.at(0) = 0; priority_queue,vector>,greater<>> Q; Q.push({0,0}); while(Q.size()){ auto [d,pos] = Q.top(); Q.pop(); if(dist.at(pos) != d) continue; auto [x,y] = XY.at(pos); for(int to=0; to now) dist.at(to) = now,Q.push({now,to}); } for(auto [a,b,c,d] : edge){ if(c == x && d == y) swap(a,c),swap(b,d); if(a == x && b == y){ int to = lower_bound(XY.begin(),XY.end(),pair{c,d})-XY.begin(); if(dist.at(to) > d+1) Q.push({d+1,to}),dist.at(to) = d+1; } } } cout << dist.at(n-1) << endl; }