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

int convert(vector<int>& Trash, int Shop, int Need, int m)
{
	for (int i=Shop*m; i<(Shop+1)*m;i++)
	{
		if (Trash[i]==Need) return i;
	}
}

signed main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
	int n,m;
	cin >> n >> m;
	vector<int> buff(m,0);
	vector<vector<int>> arr(n,buff);
	vector<int> all;
	int t;
	for (int i=0;i<n;i++)
	{
		for (int j=0;j<m;j++)
		{
			cin >> t;
			all.push_back(t-1);
			arr[i][t-1]++;
		}
	}
	all.push_back(-1);
	vector<set<int>> ShopsMany(m),ShopsNo(m),GoodsMany(n),GoodsNo(n);
	for (int i=0;i<n;i++)
	{
		for (int j=0;j<m;j++)
		{
			if (arr[i][j]==0)
			{
				ShopsNo[j].insert(i);
				GoodsNo[i].insert(j);
			}
			if (arr[i][j]>=2)
			{
				ShopsMany[j].insert(i);
				GoodsMany[i].insert(j);
			}
		}
	}
	//process
	int iterations = 0;
	vector<int> note;
	while(true)
	{
		int last=-1;
		int ShopEmpty=-1;
		for (int i=0;i<n;i++)
		{
			if (!GoodsMany[i].empty())
			{
				last = *GoodsMany[i].begin();
				ShopEmpty = i;
				arr[i][last]--;
				if (arr[i][last]==1)
				{
					GoodsMany[i].erase(last);
					ShopsMany[last].erase(i);
				}
				iterations++;
				int pos1 = convert(all,i,last,m);
				note.push_back(pos1);
				int pos2 = m*n;
				int q = all[pos1];
				all[pos1]=all[pos2];
				all[pos2]=q;
				break;
			}
		}
		if (last==-1) break;
		while(true)
		{
			int Target = *GoodsNo[ShopEmpty].begin();
			if (ShopsMany[Target].empty())
			{
				arr[ShopEmpty][Target]++;
				GoodsNo[ShopEmpty].erase(Target);
				ShopsNo[Target].erase(ShopEmpty);
				iterations++;
				note.push_back(n*m);
				break;
			}
			else
			{
				int NeedShop = *ShopsMany[Target].begin();
				arr[ShopEmpty][Target]++;
				GoodsNo[ShopEmpty].erase(Target);
				ShopsNo[Target].erase(ShopEmpty);
				arr[NeedShop][Target]--;
				if (arr[NeedShop][Target]==1)
				{
					GoodsMany[NeedShop].erase(Target);
					ShopsMany[Target].erase(NeedShop);
				}
				iterations++;
				int pos1 = convert(all,NeedShop, Target,m);
				note.push_back(pos1);
				
				int pos2 = note[note.size()-2];
				
				int q = all[pos1];
				all[pos1]=all[pos2];
				all[pos2]=q;
				ShopEmpty = NeedShop;
			}
		}
	}
	cout << iterations << endl;
	int tail = n*m+1;
	for (auto i:note)
	{
		cout << i+1 << ' ' << tail << endl;
		tail = i+1;
	}
}
