#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#define pi 3.14159265358979323846
#define sqr(a) (a)*(a)
#define v vector
#define ll long long
#define ld long double
#define f first
#define sec second
#define pb push_back
#define pf push_front
#define umap unordered_map
#define sort(a) sort(a.begin(),a.end())
#define rev(a) reverse(a.begin(),a.end())
#define yes cout<<"YES"<<endl
#define no cout<<"NO"<<endl
#define mod 1000000007
#define inf 2*1e18

using namespace std;
using namespace __gnu_pbds;

typedef tree<ll,null_type,less<ll>,rb_tree_tag,tree_order_statistics_node_update>uset;

int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    srand(time(NULL));
    ll n,m,k,i,j,x,u,mx,y;
    cin>>n>>m;
    k=n*m;
    v<ll>a(k),cnt(m);
    v<set<ll>>st(n),mas(m);
    v<pair<ll,ll>>res;
    v<bool>b(n*m,1);
    for (i=0;i<k;i++){
        cin>>a[i];
        a[i]--;
    }
    for (i=0;i<n;i++){
        for (j=0;j<m;j++){
            st[i].insert(j);
            cnt[j]=0;
        }
        for (j=0;j<m;j++){
            if (st[i].find(a[i*m+j])!=st[i].end()){
                st[i].erase(a[i*m+j]);
            }
        }
        for (j=0;j<m;j++){
            if (cnt[a[i*m+j]]){
                mas[a[i*m+j]].insert(i*m+j);
            }else{ 
                cnt[a[i*m+j]]++;
                b[i*m+j]=0;
            }
        }
    }
    for (i=0;i<k;i++){
        if (b[i]){
            x=i;
            for (j=0;j<m;j++){
                if (mas[j].find(x)!=mas[j].end()){
                    mas[j].erase(x);
                }
            }
            res.pb({x+1,k+1});
            while (1){
                mx=0;
                u=-1;
                for (auto p : st[x/m]){
                    if (mx<mas[p].size()){
                        u=p;
                        mx=mas[p].size();
                    }
                }
                if (u==-1){
                    break;
                }
                st[x/m].erase(u);
                y=*mas[u].begin();
                b[y]=0;
                res.pb({y+1,x+1});
                x=y;
                mas[u].erase(y);
            }
            b[x]=0;
            res.pb({k+1,x+1});
        }
    }
    cout<<res.size()<<endl;
    for (auto pa : res){
        cout<<pa.f<<' '<<pa.sec<<endl;
    }
    return 0;
}
