#include using namespace std; int main() { int H, W, N; cin >> H >> W >> N; vector A(N), B(N), C(N), D(N); for (int i = 0; i < N; ++i) cin >> A[i] >> B[i] >> C[i] >> D[i]; using V = pair; // i, j using E = tuple; // cost, i, j map> G; for (int i = 0; i < N; ++i) { G[{1, 1}].emplace_back(A[i]-1 + B[i]-1, A[i], B[i]); G[{1, 1}].emplace_back(C[i]-1 + D[i]-1, C[i], D[i]); for (int j = 0; j < N; ++j) if (i != j) { G[{A[i], B[i]}].emplace_back(abs(A[j]-A[i])+abs(B[j]-B[i]), A[j], B[j]); G[{A[i], B[i]}].emplace_back(abs(C[j]-A[i])+abs(D[j]-B[i]), C[j], D[j]); G[{C[i], D[i]}].emplace_back(abs(A[j]-C[i])+abs(B[j]-D[i]), A[j], B[j]); G[{C[i], D[i]}].emplace_back(abs(C[j]-C[i])+abs(D[j]-D[i]), C[j], D[j]); } G[{A[i], B[i]}].emplace_back(1, C[i], D[i]); G[{A[i], B[i]}].emplace_back(H-A[i] + W-B[i], H, W); G[{C[i], D[i]}].emplace_back(H-C[i] + W-D[i], H, W); } G[{1, 1}].emplace_back(H-1 + W-1, H, W); map answer; priority_queue, greater> pq; // distance, i, j pq.emplace(0, 1, 1); while (!pq.empty()) { auto const [d, i, j] = pq.top(); pq.pop(); answer.try_emplace(V(i, j), d); if (d > answer[{i, j}]) continue; for (auto const &[c, i2, j2] : G[{i, j}]) { answer.try_emplace(V(i2, j2), d+c); if (d+c <= answer[{i2, j2}]) { answer[{i2, j2}] = d+c; pq.emplace(d+c, i2, j2); } } } cout << answer[{H, W}] << endl; }