#include <bits/stdc++.h>
using namespace std;

class logger {
    int swapsNum = 0;
    std::vector<std::pair<int, int>> swaps;

public:
    void printResults() {
        std::cout << swapsNum << '\n'; 
        for (const auto& pair : this->swaps) std::cout << pair.first << ' ' << pair.second << '\n';
    }

    void addSwap(int source, int dest) {
        this->swaps.push_back(std::make_pair(source, dest));
        this->swapsNum++;
    }

    static logger* instance() {
        logger* log = new logger();
        return log;
    }
};

struct group_t {
    vector<int> absent;
    vector<std::pair<int, int>> extra;
};

group_t analyze(int i, int m, const vector<int> &data) {
    std::vector<std::vector<int>> dict(m);
    for (int j = i; j < i + m; ++j) dict[data[j]].push_back(j); 

    group_t group;
    
    for (int j = 0; j < m; ++j) {
        if (dict[j].size() == 0) { 
            group.absent.push_back(j);
        }
        else if (dict[j].size() > 1) {
            for (int q = 1; q < dict[j].size(); ++q)
                group.extra.push_back(std::make_pair(dict[j][q], j));
        }
    }

    return group;
}

int swapWithEmpty(int i, int &empty, std::vector<int> &data) {
    data[empty] = data[i];
    data[i] = 0;
    empty = i;

    logger::instance()->addSwap(i, empty);
}

int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);

	int n, m;
    cin >> n >> m;

    vector<int> data(m*n + 1);
    for (int &i : data) {
        cin >> i;
        i--;
    }

    // Sort every group
    int empty = m*n;
    for (int i = 0; i < m*n; i += m) {
        const auto group = analyze(i, m, data);

        for (int q = 0; q < group.extra.size(); ++q) {
            const auto& extra = group.extra[q];
            const auto& absent = group.absent[q];

            swapWithEmpty(extra.first, empty, data);
        }
    }

    logger::instance()->printResults();

    return 0;
}
