#include<iostream>
#include<vector>
#include<sstream>
using namespace std;
int rows = 0;
int cols = 0;
vector<string> inputList;
vector<vector<string>> gridCopy;
vector<vector<int>> coordinates;
void readInput(vector<string>& inputList)
{
string line = "";
while(getline(cin, line))
{
if(line == "0")
{
break;
}
else
{
inputList.push_back(line);
}
}
}
void initGrids(vector<string>& inputList)
{
rows = inputList.size();
cols = (rows > 0) ? inputList[0].size() : 0;
vector<vector<string>> grid(rows, vector<string>(cols));
gridCopy = vector<vector<string>>(rows, vector<string>(cols));
for(int i = 0; i < rows; i++)
{
istringstream iss(inputList[i]);
for(int j = 0; j < cols; j++)
{
iss >> grid[i][j];
gridCopy[i][j] = grid[i][j];
}
}
}
int countNoOccurences()
{
int count = 0;
for(const auto& row : gridCopy)
{
for(const auto& cell : row)
{
if(cell == "NO")
{
count++;
}
}
}
return count;
}
vector<vector<int>> findYesCoords()
{
vector<vector<int>> YesCoords;
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < cols; j++)
{
if(gridCopy[i][j] == "YES")
{
YesCoords.push_back({i, j});
}
}
}
return YesCoords;
}
void updateAdjElems(int i, int j)
{
vector<vector<int>> directions = {{-1, 0}, {1, 0}, {0, -1},{0, 1}};
for(const auto& dir : directions)
{
int newRow = i + dir[0];
int newCol = j + dir[1];
if(newRow >= 0 && newRow < rows && newCol >= 0 && newCol < cols && gridCopy[newRow][newCol] == "NO")
{
gridCopy[newRow][newCol] = "YES";
coordinates.push_back({newRow, newCol});
}
}
}
void printDayOrMinusOne(int noNums, int day)
{
cout << ((noNums == 0) ? to_string(day) : "-1") << endl;
}
int main()
{
vector<string> inputList;
readInput(inputList);
initGrids(inputList);
int noNums = countNoOccurences();
bool flag = true;
int day = 0;
coordinates = vector<vector<int>>();
while(noNums != 0 && flag)
{
for(const auto& coordinate : findYesCoords())
{
updateAdjElems(coordinate[0], coordinate[1]);
}
if(!coordinates.empty())
{
noNums -= coordinates.size();
coordinates.clear();
day++;
}
else
{
flag = false;
}
}
printDayOrMinusOne(noNums, day);
return 0;
}