const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;
void (async function () {
const matrix = [];
while ((line = await readline())) {
if (line == " ") break;
matrix.push(line.split(" "));
}
const len = matrix.length;
const tate = matrix[0].length;
let ans = 0;
const queue = [];
let need = 0;
for (let i = 0; i < len; i++) {
for (let j = 0; j < tate; j++) {
if (matrix[i][j] == "YES") {
queue.push([i, j]);
} else if (matrix[i][j] == "NO") {
need++;
}
}
}
const offsets = [
[0, 1],
[1, 0],
[0, -1],
[-1, 0],
];
if (queue.length == 0) return console.log(-1);
if (need == 0) return console.log(0);
while (queue.length > 0) {
const size = queue.length;
for (let i = 0; i < size; i++) {
const [x, y] = queue.shift();
for (const [dx, dy] of offsets) {
const nx = x + dx;
const ny = y + dy;
if (
nx >= 0 &&
nx < len &&
ny >= 0 &&
ny < tate &&
matrix[nx][ny] == "NO"
) {
matrix[nx][ny] = "YES";
queue.push([nx, ny]);
need--;
}
}
}
if (queue.length > 0) ans++;
}
if (need == 0) return console.log(ans);
else return console.log(-1);
})();