#include <bits/stdc++.h>

using namespace std;
typedef long long ll;
#define endl '\n'
const int N = 400+7;
vector<int> V[N][N];
int cnt[N],A[N*N];
int vis[N];
#define left asfad
set<pair<int,int> > G[N*2];
set<pair<int,int> > cp[N*2];
vector<int> seq;
vector<int> cyc;
void dfs(int v){

    while(!G[v].empty()){
        int to = G[v].rbegin()->first;
        G[v].erase(prev(G[v].end()));
        dfs(to);

    }
    if (G[v].empty()){
        cyc.push_back(v);
    }
}
void solve(){
    int n,m;
    cin>>n>>m;
    int pt = 0;
    for(int i = 1;i<=n;i+=1){
        for(int j = 1;j<=m;j+=1){
            int cur; cin>>cur;
            A[(i-1)*m+j] = cur;
            V[i][cur].push_back((i-1)*m+j);
        }
        for(int j = 1;j<=m;j+=1){
            cnt[i] += !V[i][j].empty();
            if (V[i][j].empty()){
                G[n+j].insert({i,--pt});
            }
            if (V[i][j].size()>1){
                while(V[i][j].size()>1){
                    int pos = V[i][j].back();
                    G[i].insert({n+j,pos});
                    V[i][j].pop_back();
                }
            }
        }
    }
    for(int i = 1;i<=n+m;i+=1){
        cp[i] = G[i];
    }
    vector<pair<int,int> > ans;
    for(int i = 1;i<=n;i+=1){
        if (!G[i].empty()){
            seq.clear();
            cyc.clear();
            dfs(i);
            reverse(cyc.begin(),cyc.end());
            for(int to:cyc){
                if (G[to].size()==0){
                    G[to] = cp[to];
                }
            }
            cyc.push_back(i);
            int cur = i;
            for(int nxt:cyc){
                if (cur==nxt){
                    continue;
                }
                auto e = G[cur].lower_bound({nxt,pt});
                if (e->second>0){
                    seq.push_back(e->second);
                }
                G[cur].erase(e);
                cur = nxt;
            }
            int last = n*m+1;
            while(!seq.empty()){
                ans.push_back({seq.back(),last});
                last = seq.back();
                seq.pop_back();
            }
            ans.push_back({n*m+1,last});
        }
    }
    cout<<ans.size()<<endl;
    for(auto [a,b]:ans){
        cout<<a<<' '<<b<<endl;
        swap(A[a],A[b]);
    }
    for(int i = 1;i<=n*m;i+=m){
        for(int j = 1;j<=m;j+=1){
            vis[j] = 0;
        }
        for(int j = i;j<i+m;j+=1){
            if (vis[A[j]]){
                assert(0);
            }
            vis[A[j]] = 1;
        }

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