#pragma GCC Optimize("O3")
#include "bits/stdc++.h"

using namespace std;

typedef int ll;
typedef pair<ll,ll>pairll;
typedef long double ld;

#define pb push_back
#define fr first
#define sc second
#define INF 1000000000000000007
#define MOD 1000000007
#define endl '\n'

ll n,m,d[160007],f[407],l[407];

queue<ll>a[407],q[407];

queue<pairll>res;

set<ll>s1,s2;

ll S(ll x){
    if(l[x]==1)return x;
    l[x]=1;
    ll r=S(a[(q[x].front()+m-1)/m].front());
    if(r>0){
        s1.insert(x);
        s2.insert(q[x].front());
    }
    if(r==x){
        return -r;
    }
    return r;
}

int main() {

    cin>>n>>m;
    for(int i=1;i<=n*m;i++){
        cin>>d[i];
    }
    for(int i=1;i<=n;i++){
        for(int j=1;j<=m;j++){
            f[j]=0;
        }
        for(int j=(i-1)*m+1;j<=(i-1)*m+m;j++){
            if(f[d[j]]==0){
                f[d[j]]=1;
            }else{
                q[d[j]].push(j);
            }
        }
        for(int j=1;j<=m;j++){
            if(f[j]==0){
                a[i].push(j);
            }
        }
    }
    ll x=0;
    ll y=0;
    while(1){
        x=0;
        y=0;
        for(int i=1;i<=m;i++){
            l[i]=0;
            if(q[i].size()>0){
                x=i;
                break;
            }
        }
    
        if(x==0)break;
        s1.clear();
        s2.clear();
        y=-S(x);
        ll k=q[y].size();
        //cout<<k<<" "<<y<<endl;
        while(k>0){
            if(s2.count(q[y].front())==0){
                break;
            }
            k--;
            q[y].push(q[y].front());
            q[y].pop();
        }
        x=q[y].front();
        q[y].pop();
        res.push({x,n*m+1});
        while(1){
            ll z=(x+m-1)/m;
            ll k=a[z].size();
            while(k>0){
                if(s1.count(a[z].front())==0)break;
                a[z].push(a[z].front());
                a[z].pop();
                k--;
            }
            ll h=a[z].front();
            a[z].pop();
            k=q[h].size();
            while(k>0){
                if(s2.count(q[h].front())==0){
                    break;
                }
                k--;
                q[h].push(q[h].front());
                q[h].pop();
            }
            if(h==y && q[h].size()==0){
                res.push({n*m+1,x});
                break;
            }
            ll g=q[h].front();
            q[h].pop();
            res.push({g,x});
            x=g;
        }
    }
    cout<<res.size()<<endl;
    while(res.size()>0){
        cout<<res.front().fr<<" "<<res.front().sc<<endl;
        res.pop();
    }
    
    return 0;

}
