#include <iostream>
#include <queue>
#include <fstream>
using namespace std;
ifstream f("rj.in");
ofstream g("rj.out");
queue < pair <int, int> > coada;
int di[] = {-1, -1, 0, 1, 1, 1, 0, -1};
int dj[] = {0, 1, 1, 1, 0, -1, -1, -1};
int mapRomeo[101][101];
int mapJulieta[101][101];
int n, m;
int starti_rom, startj_rom;
int starti_jul, startj_jul;
void citire(){
f >> n >> m;
f.get();
for(int i = 1; i <= n; i++){
char c;
for(int j = 1; j <= m; j++){
c = f.get();
if(c == 'R'){
starti_rom = i;
startj_rom = j;
}
else if(c == 'J'){
starti_jul = i;
startj_jul = j;
}
else if(c == 'X'){
mapRomeo[i][j] = -1;
mapJulieta[i][j] = -1;
}
else{
mapRomeo[i][j] = 0;
mapJulieta[i][j] = 0;
}
}
f.get();
}
}
bool OK(int i, int j){
if(i < 1 || j < 1 || i > n || j > m)
return false;
else return true;
}
void rez(int mat[][101], int starti, int startj){
int i, j, i_urmator, j_urmator;
mat[starti][startj] = 1;
coada.push(make_pair(starti, startj));
while( !coada.empty() ){
i = coada.front().first;
j = coada.front().second;
coada.pop();
for(int d = 0; d < 8; d++){
i_urmator = i+di[d];
j_urmator = j+dj[d];
if(OK(i_urmator, j_urmator) && !mat[i_urmator][j_urmator]){
mat[i_urmator][j_urmator] = mat[i][j]+1;
coada.push(make_pair(i_urmator, j_urmator));
}
}
}
}
int main()
{
citire();
rez(mapRomeo, starti_rom, startj_rom);
rez(mapJulieta, starti_jul, startj_jul);
//int minim = 101;
int pozi, pozj;
bool ok = true;
for(int i = 1; i <= n; i++)
for(int j = 1; j <= m; j++)
if(mapRomeo[i][j] == mapJulieta[i][j] && mapJulieta[i][j] > 0){
if(ok){
pozi = i;
pozj = j;
ok = false;
}
else if(mapRomeo[i][j] < mapRomeo[pozi][pozj]){
pozi = i;
pozj = j;
}
}
g << mapRomeo[pozi][pozj] << ' ' << pozi << ' ' << pozj;
for(int i = 1; i <= n; i++, cout << '\n')
for(int j = 1; j <= m; j++)
cout << mapRomeo[i][j] << ' ';
cout << '\n';
for(int i = 1; i <= n; i++, cout << '\n')
for(int j = 1; j <= m; j++)
cout << mapJulieta[i][j] << ' ';
return 0;
}