#include <bits/stdc++.h>

using namespace std;
typedef long long ll;
typedef string str;
typedef pair<ll, ll> pll;
const ll MAXNUM=160007;
ll n, m, a[MAXNUM], place, curr_num, pointer, step_num, border, full[403];
pll steps[MAXNUM];
multiset<ll> num_in_block, num_in_block2;
ll find_out(ll bn,ll num){
    for(int i=bn+1; i<n; i++){
        if(full[i]==0){
            auto iter=find(a+1+i*m, a+(i+1)*m, num);
            ll p=iter-a;
            if(a[p]==num) return p;
        }
    }
    return m*n+1;
}
int main()
{
    scanf("%lld %lld", &n, &m);
    border=m*n+1;
    for(int i=1; i<=n*m; i++) scanf("%lld", &a[i]);
    for(int i=0; i<n; i++){
        num_in_block.clear();
        for(int j=1; j<=m; j++){
            curr_num=i*m+j;
            num_in_block.insert(a[curr_num]);
        }
        full[i]=1;
        for(ll j=1; j<=m; j++) if(num_in_block.count(j)==0){full[i]=0; break;}
    }
    for(int i=0; i<n; i++){
        num_in_block.clear();
        if(full[i]==0){
            for(int j=1; j<=m; j++){
                curr_num=i*m+j;
                num_in_block.insert(a[curr_num]);
            }
            pointer=i*m+1;
            for(ll j=1; j<=m; j++){
                if(num_in_block.count(j)==0){
                    while(num_in_block.count(a[pointer])<=1 && a[pointer]!=0) pointer++;
                    if(a[pointer]!=0){
                        swap(a[border], a[pointer]);
                        step_num++;
                        steps[step_num]={pointer, border};
                        place=find_out(i, j);
                        swap(a[place], a[pointer]);
                        step_num++;
                        steps[step_num]={place, pointer};
                        border=place;
                    }
                    else{
                        place=find_out(i, j);
                        swap(a[place], a[pointer]);
                        step_num++;
                        steps[step_num]={place, pointer};
                        border=place;
                    }
                }
            }
            full[i]=1;
        }
        else pointer+=m;
    }
    cout << step_num << "\n";
    for(int i=1; i<=step_num; i++){
        cout << steps[i].first << ' ' << steps[i].second << "\n";
    }
    return 0;
}
