#include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
//#pragma GCC optimize("unroll-loops")
//#pragma GCC optimize("avx2")

using namespace std;

#define x first
#define y second
#define pb push_back
#define all(a) a.begin(),a.end()
#define int long long

typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
typedef pair<int,int>pii;
typedef pair<ll,ll>pll;
typedef vector<ll>vll;
typedef vector<int>vi;
typedef vector<bool>vb;
typedef vector<vi>vvi;
typedef vector<vll>vvll;
typedef vector<pii>vpii;
typedef vector<pll>vpll;

const int N=4e2+44;
const char nl='\n';

int val[N*N],a[N][N],cnt[N][N];
vi need[N];
set<int>extra[N];

void solve(){
    int n,m;
    cin>>n>>m;
    set<int>pos;
    for(int i=1;i<=n;++i){
        for(int j=1;j<=m;++j){
            cin>>a[i][j];
            cnt[i][a[i][j]]++;
            val[(i-1)*m+j]=a[i][j];
            if(cnt[i][a[i][j]]>1){
                pos.insert((i-1)*m+j);
                extra[a[i][j]].insert((i-1)*m+j);
            }
        }
        for(int j=1;j<=m;++j){
            if(cnt[i][j]==0){
                need[i].pb(j);
            }
        }
    }
    vpii ans;
    int last=n*m+1,cur=0;
    while(!pos.empty()){
        if(val[last]==0){
            cur=*pos.begin();
            pos.erase(pos.begin());
            pos.insert(last);
            val[last]=val[cur];
            extra[val[cur]].erase(cur);
            extra[val[cur]].insert(last);
            val[cur]=0;
            ans.pb({cur,last});
        }
        else{
            int ind=(cur-1)/m+1;
            auto it=extra[need[ind].back()].upper_bound(ind*m);
            if(it==extra[need[ind].back()].end()){
                it=extra[need[ind].back()].begin();
            }
            int new_cur=*it;
            pos.erase(new_cur);
            extra[need[ind].back()].erase(new_cur);
            need[ind].pop_back();
            val[cur]=val[new_cur];
            val[new_cur]=0;
            ans.pb({new_cur,cur});
            cur=new_cur;
        }
    }
    cout<<ans.size()<<nl;
    for(auto[x,y]:ans){
        cout<<x<<' '<<y<<nl;
    }
}

signed main(){
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    int t=1;
//    cin>>t;
    while(t--){
        solve();
    }
}
