function bomb(){
   var ans=0;
   var dx=[0,-1,1,0];
   var dy=[-1,0,0,1];
   var obj={};
   var ary=[[1,1,0]];
   while(true){
      if(ary.length==0)break;
      var leaf=ary.shift();
      var x=leaf[0];
      var y=leaf[1];
      var cnt=leaf[2];
      if(x==w*2-1 && y==h*2-1){ans=(cnt+2)/2;break;}
      for(var i=0;i<4;i++){
         var X=x+dx[i];
         var Y=y+dy[i];
         if(X<=0 || Y<=0 || X>=w*2 || Y>=h*2)continue;
         if(yx[Y][X]==1)continue;
         if(obj.hasOwnProperty(X+","+Y)==false){
            ary.push([X,Y,cnt+1]);
            obj[X+","+Y]=true;
         }
      }
   }
   return ans;
}
var input = require('fs').readFileSync('/dev/stdin', 'utf8');
var arr=input.trim().split("\n");
while(true){
   var wh=arr.shift().split(" ").map(Number);
   if(wh.join(" ")=="0 0")break;
   var w=wh[0];
   var h=wh[1];
   var yx=[];
   for(var i=0;i<=h*2;i++){
      yx[i]=[];
      for(var j=0;j<=w*2;j++){
         yx[i][j]=0;
      }
   }
   for(var i=0;i<(h*2)-1;i++){
      var data=arr.shift().replace(/ /g,"");
      if(i%2==0){
         data=data;
         var ary=data.split("");
         ary.forEach(function(value,index){
            if(value=="1"){
               yx[i+0][index*2+2]=1;
               yx[i+1][index*2+2]=1;
               yx[i+2][index*2+2]=1;
            }
         });
      }else{
         var ary=data.split("");
         ary.forEach(function(value,index){
            if(value=="1"){
               yx[i+1][index*2+0]=1;
               yx[i+1][index*2+1]=1;
               yx[i+1][index*2+2]=1;
            }
         });
      }
   }
   console.log(bomb());
}