#include <bits/stdc++.h>

using namespace std;

const int N = 401;
int a[N][N];
int rowCnt[N][N];
int n, m;
vector<pair<int, int>> ops;

void doOp(int i1, int j1, int i2, int j2) {
    ops.push_back({i1 * m + j1, i2 * m + j2});
    --rowCnt[i1][a[i1][j1]];
    ++rowCnt[i1][a[i2][j2]];

    --rowCnt[i2][a[i2][j2]];
    ++rowCnt[i2][a[i1][j1]];

    swap(a[i1][j1], a[i2][j2]);
}

void doRecOp(int i, int j, int val = 0) {
    while (val < m && rowCnt[i][val]) ++val;
    if (val == m) {
        doOp(n, 0, i, j);
        return;
    }
    int i2 = 0;
    while (i2 < n && rowCnt[i2][val] < 2) ++i2;
    if (i2 == n) {
        doRecOp(i, j, val + 1);
        return;
    }
    int j2 = 0;
    while (a[i2][j2] != val) {
        ++j2;
    }
    doOp(i2, j2, i, j);
    doRecOp(i2, j2);
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cin >> n >> m;
    for (int i = 0; i < n; ++i) {
        fill(rowCnt[i], rowCnt[i] + N, 0);
        for (int j = 0; j < m; ++j) {
            cin >> a[i][j];
            --a[i][j];
            ++rowCnt[i][a[i][j]];
        }
    }
    fill(rowCnt[n], rowCnt[n] + N, 0);
    a[n][0] = m;
    ++rowCnt[n][m];
    bool canChange = true;
    while (canChange) {
        canChange = false;
        int minNotEx = m, ind = 0;
        for (int i = 0; i < n; ++i) {
            int curr = 0;
            for (int j = 0; j < m; ++j) {
                if (!rowCnt[i][j]) {
                    ++curr;
                }
            }
            if (curr < minNotEx) {
                minNotEx = curr;
                ind = i;
            }
        }
        int i = ind;
        for (int j = 0; j < m; ++j) {
            if (rowCnt[i][a[i][j]] > 1) {
                canChange = true;
                doOp(i, j, n, 0);
                doRecOp(i, j);
                break;
            }
        }
    }
    cout << ops.size() << '\n';
    for (auto [i, j] : ops) {
        cout << i + 1 << ' ' << j + 1 << '\n';
    }
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < m; ++j) {
            cerr << a[i][j] << ' ';
        }
        cerr << '\n';
    }
    return 0;
}
