#include<bits/stdc++.h>
using namespace std;
const int mn=4e5+5;
int n,m,top,cnt,sum,x,y,t,o,a1[mn],a2[mn];
stack<int> a[mn],b;
void move (int x,int y,int tot){
for(int i=1;i<=tot;i++){
a[y].push(a[x].top());
a1[++o]=x,a2[o]=y;
a[x].pop();
}
return ;
}
int search (int x,int tot){
int y=0;
while(!a[x].empty()){
b.push(a[x].top());
if(a[x].top()==tot)y++;
a[x].pop();
}
while(!b.empty()){
a[x].push(b.top());
b.pop();
}
return y;
}
void swap(int x,int y){
while(!a[x].empty()){
b.push(a[x].top());
a[x].pop();
}
while(!a[y].empty()){
a[x].push(a[y].top());
a[y].pop();
}
while(!b.empty()){
a[y].push(b.top());
b.pop();
}
}
int cntt (int x){
int y=0;
while(!a[x].empty()){
b.push(a[x].top());
y++;
a[x].pop();
}
while(!b.empty()){
a[x].push(b.top());
b.pop();
}
return y;
}
int main(){
cin>>n>>m;
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
cin>>x;
a[i].push(x);
}
}
for(int i=n;i>=3;i--){
cnt=search(1,i);
move(i,i+1,cnt);
for(int j=1;j<=m;j++){
if(a[1].top()==i){
move(1,i,1);
}
else move(1,i+1,1);
}
move(i+1,1,m-cnt);
for (int j=1;j<=m;j++){
if(a[2].top()==i || cntt(1)==m)move(2,i+1,1);
else move(2,1,1);
}
swap(1,i);
swap(2,i+1);
for(int j=1;j<=i;j++){
cnt=search(j,i);
move(i,i+1,cnt);
for (int k=1;k<=m;k++){
if (a[j].top()==i) move(j,i,1);
else move(j,i+1,1);
}
swap(j,i+1);
swap(j,i);
}
for (int j=1;j<i;j++){
while (a[j].top()==i) move(j,i+1,1);
}
for (int j=1;j<i;j++){
while (cntt(j)<m) move(i,j,1);
}
}
cnt=search(1,1);
for (int i=1;i<=cnt;i++) move(2,3,1);
for (int i=1;i<=m;i++){
if (a[1].top()==1) move(1,2,1);
else move(1,3,1);
}
move(2,1,cnt);
move(3,1,m-cnt);
move(3,2,cntt(3));
move(1,3,m-cnt);
for (int i=1;i<=m;i++){
if (a[2].top()==1) move(2,1,1);
else move(2,3,1);
}
cout<<o<<"\n";
for(int i=1;i<=o;i++){
cout<<a1[i]<<" "<<a2[i]<<"\n";
}
return 0;
}