def g;gets.split.map &:to_i;end
while(x,y=g;x>0)
a=g
b=g
a==b&&p(0)&&next
h={}
q=[a+b<<0]
m=(1..y).map{g}
while(*a,e=q.shift;e&&e<99)
h[a]=e
l=[[0,1],[1,0],[0,-1],[-1,0]]
(0..3).all?{|i|
  t,u,v,w=a.zip(l[i]+l[i-2]).map{|j,k|[j,j+k]}
  c,d=[[t,u],[v,w]].map{|(i,j),(k,n)|j>=0&&j<y&&n>=0&&n<x&&m[j][n]==0&&[j,n]||[i,k]}
  c!=d&&(h[c+d]||q<<c+d+[e+1])
}||break
end
puts e ?e+1:"NA"
end