import std.stdio;
import std.algorithm;
import std.string;
import std.functional;
import std.array;
import std.conv;
import std.math;
import std.typecons;
import std.regex;
import std.range;
int[] d = [-1,1];
int h,w;
int[][] hwall,wwall;

int saiki(){

    Tuple!(int,int)[] queuex,queuey;
    int x,y;
    bool[31][31] used;
    foreach(i;used)foreach(j;i) j = false;
    int ans = 2;
    int temp;
    int c;
    queuex ~= tuple(x,1);
    queuey ~= tuple(y,1);
    while(c < to!int(queuex.length)){
	x = queuex[c][0];
	y = queuey[c][0];
	ans = queuex[c][1];
	c++;
	if(x == w-1 && y == h-1){
	    return ans;
	}

	foreach(i;d){
	    if(x+i>=w || x+i < 0 ) continue;
	    if(i == -1 && wwall[y][x]) continue;
	    if(i != -1 && wwall[y][x+i]) continue;
	    if(used[y][x+i]) continue;
	    used[y][x+i] = true;
	    queuex ~= tuple(x+i,ans+1);
	    queuey ~= tuple(y,ans+1);
	}
	foreach(i;d){
	    if(y+i>=h || y+i < 0 ) continue;
	    if(i == -1 && hwall[y][x]) continue;
	    if(i != -1 && hwall[y+i][x]) continue;
	    if(used[y+i][x]) continue;
	    used[y+i][x] = true;
	    queuex ~= tuple(x,ans+1);
	    queuey ~= tuple(y+i,ans+1);
	}
    }
    return 0;
}

void main(){

    while(true){
	int[][] th,tw;
	auto s = readln().split().to!(int[]);
	if(s[0] == 0 && s[1] == 0) break;
	w = s[0];
	h = s[1];

	th ~= new int[31];
	tw ~=  0 ~ readln().split().to!(int[]);
	for(int i=0;i<h-1;i++){
	    th ~=  readln().split().to!(int[]);
	    tw ~=  0 ~ readln().split().to!(int[]);
	}
	hwall = th.dup();
	wwall = tw.dup();
	writeln(saiki());
    }

}