#include <iostream>
#include <vector>
#include <set>

using namespace std;

int main()
{
    cin.tie(0)->sync_with_stdio(0);
    int n, m;
    cin >> n >> m;
    vector<int> a(n * m);
    for (int &i : a)
    {
        cin >> i;
        --i;
    }
    a.push_back(-1);
    vector<vector<int>> adj(n + m);
    for (int i = 0; i < n; ++i)
    {
        vector<int> counter(m);
        for (int j = i * m; j < (i + 1) * m; ++j) ++counter[a[j]];
        for (int j = 0; j < m; ++j)
        {
            if (counter[j] == 0) adj[n + j].push_back(i);
            else if (counter[j] > 1)
            {
                for (int k = 1; k < counter[j]; ++k)
                {
                    adj[i].push_back(n + j);
                }
            }
        }
    }
    vector<int> path;
    vector<vector<int>> used(n + m);
    vector<int> ind(n + m);
    for (int i = 0; i < n + m; ++i) used[i].resize(adj[i].size());
    auto dfs = [&adj, &path, &ind, &used](auto self, int v) -> void
    {
        for (; ind[v] < adj[v].size(); ++ind[v])
        {
            if (!used[v][ind[v]])
            {
                used[v][ind[v]] = true;
                self(self, adj[v][ind[v]]);
            }
        }
        path.push_back(v);
    };
    vector<pair<int, int>> res;
    auto findI = [&a, &m](int i, int val) -> int
    {
        for (int j = i * m; j < (i + 1) * m; ++j)
        {
            if (a[j] == val)
            {
                return j;
            }
        }
        return -1;
    };
    for (int i = 0; i < n; ++i)
    {
        if (ind[i] == 0)
        {
            path.clear();
            dfs(dfs, i);
            if (path.size() == 1) continue;
            int v = findI(path.front(), path[(int)path.size() - 2] - n);
            res.emplace_back(v, n * m);
            swap(a[v], a[n * m]);
            for (int i = 1; i + 2 < path.size(); i += 2)
            {
                int next = findI(path[i + 1], path[i] - n);
                swap(a[next], a[v]);
                res.emplace_back(next, v);
                v = next;
            }
            res.emplace_back(n * m, v);
            swap(a[v], a[n * m]);
        }
    }
    cout << res.size() << '\n';
    for (auto [a, b] : res) cout << a + 1 << ' ' << b + 1 << '\n';
//1 2 3 4 0
    //2 4 1 3 0
    //0 4 1 3 2
    //1 4 0 3 2
    //1 4 3 0 2
    //1 0 3 4 2
    //1 2 3 4 0
    /*
    1 2 3  1
    2 3 1  1
    1 3 2  2
    3 2 1  1 === 5
    3
    */
    /*
    1 2 3 3
    1 2 4 4
    1 2 4 4
    1 2 3 3
    0
    */
    /*
    5 6
    2 3 6 4 1 5  1
    2 4 6 1 3 5  1
    1 5 4 2 3 6  2
    3 6 4 5 1 2  1
    5 1 4 2 3 6  2
    */
    //0
    return 0;
}
