#include <bits/stdc++.h>   using namespace std;   const int mod = 1e4 + 7;   const long long INF = 1e18;   const int maxn = 6e5 + 5;   int n, m, k;   struct edge {     int to, cost;     edge() {}     edge(int to, int cost) : to(to), cost(cost) {}   };   vector<edge> G[maxn];   int d[maxn];   pair<int, int> p[maxn];   map<pair<int, int>, int> mp;   int dx[4] = {0, 0, 1, -1};   int dy[4] = {1, -1, 0, 0};   void dijkstra(int s) {     priority_queue<pair<int, int>, vector<pair<int, int> >,                    greater<pair<int, int> > >         q;     fill(d, d + maxn, 0x7fffffff);     d[s] = 0;     q.push(pair<int, int>(0, s));     while (!q.empty()) {       pair<int, int> p = q.top();       q.pop();       int v = p.second;       if (d[v] < p.first) continue;       for (int i = 0; i < G[v].size(); i++) {         edge e = G[v][i];         if (d[e.to] > d[v] + e.cost) {           d[e.to] = d[v] + e.cost;           q.push(pair<int, int>(d[e.to], e.to));         }       }     }   }   int main() {     cin >> n >> m >> k;     int dd = 1e4 + 5;     mp.clear();     for (int i = 1; i <= k; i++) {       int r, c;       scanf( %d%d , &r, &c);       G[i].push_back(edge(r + dd, 1));       G[i].push_back(edge(c + dd * 2, 1));       G[i].push_back(edge(r + 1 + dd, 1));       G[i].push_back(edge(r - 1 + dd, 1));       G[i].push_back(edge(c + dd * 2 + 1, 1));       G[i].push_back(edge(c + dd * 2 - 1, 1));       G[r + dd].push_back(edge(i, 0));       G[c + dd * 2].push_back(edge(i, 0));       G[r + 1 + dd].push_back(edge(i, 0));       G[r - 1 + dd].push_back(edge(i, 0));       G[c + dd * 2 + 1].push_back(edge(i, 0));       G[c + dd * 2 - 1].push_back(edge(i, 0));       p[i] = pair<int, int>(r, c);       mp[pair<int, int>(r, c)] = i;     }     for (int i = 1; i <= k; i++) {       for (int j = 0; j < 4; j++) {         int x = p[i].first + dx[j];         int y = p[i].second + dy[j];         if (mp.find(pair<int, int>(x, y)) != mp.end())           G[i].push_back(edge(mp[pair<int, int>(x, y)], 0));       }     }     if (mp.find(pair<int, int>(n, m)) == mp.end()) {       G[n + dd].push_back(edge(k + 1, 0));       G[m + 2 * dd].push_back(edge(k + 1, 0));     }     int ans;     dijkstra(mp[pair<int, int>(1, 1)]);     if (mp.find(pair<int, int>(n, m)) == mp.end()) {       ans = d[k + 1];     } else       ans = d[mp[pair<int, int>(n, m)]];     if (ans == 0x7fffffff) ans = -1;     cout << ans << endl;   }   