#include<iostream>
#include<queue>
#include<utility>
using namespace std;

typedef pair<int,int> P;

int main(){
  int w,h;
  bool vw[50][50],pw[50][50];
  int grid[50][50];

  while(cin >> w >>h , w||h){
    for(int i=0;i<h;i++){
      for(int j=0;j<w-1;j++)cin >> vw[i][j];
      if(i!=h-1)for(int j=0;j<w;j++)cin >> pw[i][j];
    }

    for(int i=0;i<h;i++)
      for(int j=0;j<w;j++)grid[i][j] = 0;
    
    grid[0][0] = 1;
    queue<P> q;
    q.push(P(0,0));

    while(q.size()){
      P p = q.front(); q.pop();
      int y = p.first, x = p.second;

      if(y==h-1 && x==w-1)break;

      if(0<=y-1 && !pw[y-1][x] && !grid[y-1][x]){
	grid[y-1][x] = grid[y][x]+1;
	q.push(P(y-1,x));
      }
      if(0<=x-1 && !vw[y][x-1] && !grid[y][x-1]){
	grid[y][x-1] = grid[y][x]+1;
	q.push(P(y,x-1));
      }
      if(y+1<h && !pw[y][x] && !grid[y+1][x]){
	grid[y+1][x] = grid[y][x]+1;
	q.push(P(y+1,x));
      }
      if(x+1<w && !vw[y][x] && !grid[y][x+1]){
	grid[y][x+1] = grid[y][x]+1;
	q.push(P(y,x+1));
      }
    }
    cout << grid[h-1][w-1] << endl;
  }
}