#include <bits/stdc++.h>
using namespace std;
struct xy {
int x, y, p;
};
int h, w, sx, sy, t0, t1;
int py0[2][2] = {{0, -1}, {0, 1}}, py1[2][2] = {{-1, 0}, {1, 0}};
char mp[1005][1005];
int vis[1005][1005];
queue<xy> q;
int move0 (int tx, int ty, int t) {
for (int i = 0; i < 2; ++i) {
int ttx = tx + py0[i][0];
int tty = ty + py0[i][1];
if (ttx > h || ttx <= 0 || tty > w || tty <= 0 || mp[ttx][tty] == '#') {
continue;
}
if ((vis[ttx][tty] <= t) && vis[ttx][tty]) {
continue;
}
q.push((xy) {
ttx, tty, 0
});
vis[ttx][tty] = t;
if (mp[ttx][tty] == 'G') {
return t - 1;
}
}
return -1;
}
int move1 (int tx, int ty, int t) {
for (int i = 0; i < 2; ++i) {
int ttx = tx + py1[i][0];
int tty = ty + py1[i][1];
if (ttx > h || ttx <= 0 || tty > w || tty <= 0 || mp[ttx][tty] == '#') {
continue;
}
if ((vis[ttx][tty] <= t) && vis[ttx][tty]) {
continue;
}
q.push((xy) {
ttx, tty, 1
});
vis[ttx][tty] = t;
if (mp[ttx][tty] == 'G') {
return t - 1;
}
}
return -1;
}
int bfs () {
q.push((xy) {
sx, sy, -1
});
vis[sx][sy] = 1;
while (!q.empty()) {
int tx = q.front().x;
int ty = q.front().y;
int tp = q.front().p;
int t = vis[tx][ty] + 1;
q.pop();
if (tp == -1) {
t0 = move0(tx, ty, t);
if (t0 != -1) {
return t0;
}
t1 = move1(tx, ty, t);
if (t1 != -1) {
return t1;
}
} else if (tp == 0) {
t1 = move1(tx, ty, t);
if (t1 != -1) {
return t1;
}
} else if (tp == 1) {
t0 = move0(tx, ty, t);
if (t0 != -1) {
return t0;
}
}
}
return -1;
}
int main() {
cin >> h >> w;
for (int i = 1; i <= h; ++i) {
for (int j = 1; j <= w; ++j) {
cin >> mp[i][j];
if (mp[i][j] == 'S') {
sx = i;
sy = j;
}
}
}
cout << bfs() << "\n";
for (int i = 1; i <= h; ++i) {
for (int j = 1; j <= w; ++j) {
cout << vis[i][j] << " ";
}
cout << "\n";
}
return 0;
}