#include <cstdio>
#include <numeric>
#include <cassert>
#include <vector>

const int N = 400;
int n, m, cnt[N][N], a[N * N], was[N], last[N], prev[N], to[N * N], top[N * N];
bool u[N * N];

int find(int a) {
	if (top[a] == a) return a;
	return top[a] = find(top[a]);
}

bool merge(int a, int b) {
	a = find(a);
	b = find(b);
	if (a != b) {
		top[a] = b;
		return 1;
	}
	return 0;
}

int main() {
	scanf("%d%d", &n, &m);
	for (int i = 0; i < n * m; ++i) {
		scanf("%d", a + i);
		--a[i];
		++cnt[i / m][a[i]];
	}
	std::vector<std::pair<int, int> > ans;
	std::vector<std::vector<std::pair<int, int> > > cyc;
	for (int i = 0; i < n * m; ++i) if (cnt[i / m][a[i]] > 1) {
		std::vector<std::pair<int, int> > p;
		int j = i, cur = -1;
		while (true) {
			p.push_back(std::make_pair(j, a[j]));
			--cnt[j / m][a[j]];
			std::swap(a[j], cur);
			if (a[j] != -1) ++cnt[j / m][a[j]];
			int to;
			for (to = 0; to < n && cnt[to][cur]; ++to);
			if (to == n) to = i / m;
			if (to == i / m) {
				for (j = to * m; j < (to + 1) * m && (a[j] == -1 || cnt[to][a[j]] == 1); ++j);
				if (j == (to + 1) * m) break;
			} else for (j = to * m; cnt[to][a[j]] == 1; ++j);
		}
		a[i] = cur;
		++cnt[i / m][a[i]];
		cyc.push_back(p);
	}
	std::iota(to, to + n * m, 0);
	std::iota(top, top + n * m, 0);
	for (int i = 0; i < (int)cyc.size(); ++i) {
		for (int j = 0; j < (int)cyc[i].size(); ++j) {
			int next = j + 1 == cyc[i].size() ? 0 : j + 1;
			int u = cyc[i][j].first, v = cyc[i][next].first, col = cyc[i][j].second;
			merge(u, v);
			to[u] = v;
			if (was[col] && last[col] != i && merge(i, last[col])) {
				std::swap(to[u], to[prev[col]]);
			}
			was[col] = 1;
			last[col] = i;
			prev[col] = u;
		}
	}
	for (int i = 0; i < n * m; ++i) if (to[i] != i && !u[i]) {
		std::vector<int> p;
		int cur = i;
		do {
			u[cur] = 1;
			p.push_back(cur);
			cur = to[cur];
		} while (cur != i);
		ans.push_back(std::make_pair(p.back() + 1, n * m + 1));
		for (int i = p.size() - 2; i >= 0; --i) ans.push_back(std::make_pair(p[i] + 1, p[i + 1] + 1));
		ans.push_back(std::make_pair(n * m + 1, p.front() + 1));
	}
	for (int i = 0; i < n * m; ++i) assert(cnt[i / m][a[i]] == 1);
	printf("%d\n", (int)ans.size());
	for (int i = 0; i < (int)ans.size(); ++i) printf("%d %d\n", ans[i].first, ans[i].second);
	return 0;
}