import java.util.*;
public class ChangeEarth {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<String[]> strings = new ArrayList<>();
while(sc.hasNextLine()){
String line = sc.nextLine();
if(line.isEmpty()){
break;
}
strings.add(line.split("\\s+"));
}
String[][] strings1= new String[strings.size()][];
strings.toArray(strings1);
solve(strings1);
}
private static void solve(String[][] strings) {
for (int i = 0; i < strings.length; i++) {
for (int j = 0; j < strings[0].length; j++) {
if(strings[i][j].equals("NA")){
System.out.println("-1");
return;
}
}
}
LinkedList<int[]> queue = new LinkedList<>();
int[][] directions = new int[][]{{1,0},{0,1},{-1,0},{0,-1}};
for (int i = 0; i < strings.length; i++) {
for (int j = 0; j < strings[0].length; j++) {
if(strings[i][j].equals("YES")){
queue.add(new int[]{i,j});
}
}
}
int res = 0;
while(!queue.isEmpty()){
boolean flag = false;
int size = queue.size();
for(int jj=0;jj<size;jj++){
int[] poll = queue.poll();
for(int i=0;i<4;i++){
int x = poll[0]+directions[i][0];
int y = poll[1]+directions[i][1];
if(x<0 || x>=strings.length || y<0 || y>=strings[0].length|| strings[x][y].equals("YES")){
continue;
}
if(strings[x][y].equals("NO")){
flag=true;
strings[x][y] = "YES";
queue.add(new int[]{x,y});
}
}
}
if(flag){
res++;
}
}
System.out.println(res);
}
}