import Data.Char
import Data.List

main = interact $ unlines . map (show . mazes) . read' . lines
 where
  read' ("0 0":_) = []
  read' (wh:xs) = ((w,h),m) : read' xs'
   where
    [w,h] = map read (words wh)
    (m,xs') = splitAt (2*h-1) xs

mazes ((w,h),m) = bfs (2*(w-1),2*(h-1)) m 1 unsearched [(0,0)]
 where unsearched = tail [(x,y) | x<-[0,2..2*(w-1)], y<-[0,2..2*(h-1)]]

bfs _ _ _ [] _ = 0
bfs _ _ _ _ [] = 0
bfs e m s u c 
 | elem e c = s
 | otherwise = bfs e m (succ s) (u \\ c') c'
 where
  c' = intersect (nub (concatMap neighbor c)) u
  neighbor (x,y) = map snd (filter movable dir)
   where 
    movable ((wx,wy),(x',y')) = elem (x',y') u && m!!wy!!wx == '0'
    dir = [((x-1,y),(x-2,y)),((x+1,y),(x+2,y)),((x,y-1),(x,y-2)),((x,y+1),(x,y+2))]