#include <bits/stdc++.h>

using namespace std;
typedef long long ll;
#define endl '\n'
const int N = 400+7;
vector<int> V[N][N];
set<int> need[N],thr[N];
int cnt[N],A[N*N];
int timer = 0;
int vis[N];
#define left asfad
vector<pair<int,int> > G[N*2],left[N*2];

vector<int> seq;
void calc(int v,int &sz){
    vis[v] = timer;
    sz += 1;
    for(auto [to,pos]:G[v]){
        if (vis[to]==timer){
            continue;
        }
        calc(to,sz);
    }
}
void dfs(int v){
    if (G[v].empty()){
        G[v] = left[v];
        left[v].clear();
    }
    while(G[v].size()+left[v].size()>0){
        if (G[v].empty()){
            swap(G[v],left[v]);
        }
        int to = G[v].back().first;
        int sz1 = 0;
        calc(to,sz1);
        int sz2 = 0;
        calc(v,sz2);
        if (sz1<sz2-((G[v].size()+left[v].size()-1)==1)){
            left[v].push_back(G[v].back());
            G[v].pop_back();
            continue;
        }
        if (G[v].back().second!=0){
            seq.push_back(G[v].back().second);
        }
        G[v].pop_back();
        dfs(to);
        return;

    }
}
void solve(){
    int n,m;
    cin>>n>>m;
    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].push_back({i,0});
            }
            if (V[i][j].size()>1){
                while(V[i][j].size()>1){
                    int pos = V[i][j].back();
                    G[i].push_back({n+j,pos});
                    V[i][j].pop_back();
                }
            }
        }
    }
    vector<pair<int,int> > ans;
    for(int i = 1;i<=n;i+=1){
        if (!G[i].empty()){
            seq.clear();

            dfs(i);
            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 = i;j<i+m;j+=1){
            if (vis[A[j]]){
                assert(0);
            }
            vis[A[j]] = 1;
        }
        for(int j = 1;j<=m;j+=1){
            vis[j] = 0;
        }
    }
}
int main()
{
    ios_base::sync_with_stdio(0); cin.tie(0);
    int t = 1;
    //cin>>t;
    while(t--){
        solve();
    }
    return 0;
}