#include <stdio.h>

int w,h;
int map[30][30];
int W_LR[30][30],W_UD[30][30];
int  judge_UP(int y,int x);
int  judge_DOWN(int y,int x);
int  judge_LEFT(int y,int x);
int  judge_RIGHT(int y,int x);
void func(int y, int x,int p);

int main (void)
{
  int x,y;

  while(1){
    //ú»
    for(y=0;y<30;y++){
      for(x=0;x<30;x++){
	map[y][x]=0;
      }   
    }
    scanf("%d %d",&w,&h);
    
    if(w * h == 0)    
      break;
    
    for(y=0;y<h-1;y++){
      for(x=0;x<w-1;x++){
	scanf(" %d",&W_LR[y][x]);
      }
      for(x=0;x<w;x++){
	scanf(" %d",&W_UD[y][x]);
      }
    }
    for(x=0;x<w-1;x++){
      scanf(" %d",&W_LR[h-1][x]);
    }
    //Èã}bvÇÝÝ

    map[0][0]= 1;
    func(0,0,1);

    printf("%d\n",map[h-1][w-1]);
  }
  return 0;
}

int  judge_UP(int y,int x){
  if(y-1<0)
    return 0;
  else if(W_UD[y-1][x] ==1)
    return 0;
  else 
    return 1;
}
  
int  judge_DOWN(int y,int x){
  if(y+1>=h)
    return 0;
  else if(W_UD[y][x] ==1)
    return 0;
  else 
    return 1;
}
int  judge_LEFT(int y,int x){
  if(x-1<0)
    return 0;
  else if(W_LR[y][x-1] ==1)
    return 0;
  else 
    return 1;
}
int  judge_RIGHT(int y,int x){
  if(x+1>=w)
    return 0;
  else if(W_LR[y][x] ==1)
    return 0;
  else 
    return 1;
}

void func(int y, int x,int p){
  //UP
  if(judge_UP(y,x)){
    if(map[y-1][x] ==0){
      map[y-1][x] = p+1;
      func(y-1,x,p+1);
    }
    else{
      if(map[y-1][x] > p+1){
	map[y-1][x] = p+1;
	func(y-1,x,p+1);
      }
    }
  }
  //DOWN
  if(judge_DOWN(y,x)){
    if(map[y+1][x] ==0){
      map[y+1][x] = p+1;
      func(y+1,x,p+1);
    }
    else{
      if(map[y+1][x] > p+1){
	map[y+1][x] = p+1;
	func(y+1,x,p+1);
      }
    }
  }
  //LEFT
  if(judge_LEFT(y,x)){
    if(map[y][x-1] ==0){
      map[y][x-1] = p+1;
      func(y,x-1,p+1);
    }
    else{
      if(map[y][x-1] > p+1){
	map[y][x-1] = p+1;
	func(y,x-1,p+1);
      }
    }
  }
  //RIGHT
  if(judge_RIGHT(y,x)){
    if(map[y][x+1] ==0){
      map[y][x+1] = p+1;
      func(y,x+1,p+1);
    }
    else{
      if(map[y][x+1] > p+1){
	map[y][x+1] = p+1;
	func(y,x+1,p+1);
      }
    }
  }

}