#pragma GCC optimize("Ofast")
#include <bits/stdc++.h>
typedef long long ll;
#define endl '\n'
using namespace std;
const int N=2000010;
int a[N];
vector<pair<int,int> >g[N];
vector<int> group[N];
vector<int>order;
void dfs(int v,int pr){
    while (!g[v].empty()){
        auto cur=g[v].back();
        g[v].pop_back();
        int to=cur.first;
        dfs(to,v);
        order.push_back(cur.second);
    }
}
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    int n,m;cin>>n>>m;
    for (int i=1;i<=n*m;i++) cin>>a[i];
    for (int i=1;i<=n;i++){
        vector<int>bad;
        for (int j=1;j<=m;j++){
            if (!group[a[(i-1)*m+j]].empty()) bad.push_back((i-1)*m+j);
            group[a[(i-1)*m+j]].push_back((i-1)*m+j);
        }
        for (int j=1;j<=m;j++){
            if (group[j].empty()){
                g[j+n].push_back({i,bad.back()});
                bad.pop_back();
//                cout<<"E "<<j+n<<endl;
            } else {
                for (int t=1;t<group[j].size();t++){
                    g[i].push_back({j+n,group[j][t]});
//                    cout<<"E "<<i<<endl;
                }
            }
        }
        for (int j=1;j<=m;j++) {
            group[j].clear();
        }
    }
    vector<pair<int,int> >ans;
    for (int i=1;i<=n;i++){
        dfs(i,0);
        if (!order.empty()){
            order.pop_back();
            ans.push_back({order[0],n*m+1});
            for (int i=2;i<order.size();i+=2){
                order[i]=order[i-1];
            }
            for (int i=1;i<order.size();i++){
               // if (i%2==0 && order[i]!=order[i-1]) exit(1);
                if (i%2==0) continue;
                ans.push_back({order[i],order[i-1]});
            }
            ans.push_back({n*m+1,order.back()});
            order.clear();
        }
    }
    cout<<ans.size()<<endl;
    for (auto cur:ans) {
        if (a[cur.second]) exit(1);
        swap(a[cur.first],a[cur.second]);
        cout<<cur.first<<" "<<cur.second<<endl;
    }
    if (a[n*m+1]!=0) exit(1);

//    for (int i=1;i<=n*m+1;i++) cout<<a[i]<<" ";
//    cout<<endl;
    return 0;
}
/**
5 8
2 1
1 3
4 2
5 2
3 4
3 5
4 5
5 4
**/
