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[31][31] dp;


int saiki(int x,int y,bool[31][31] used){

    used[y][x] = true;
    if(dp[y][x] > 0 ) return dp[y][x];
    if(x==w-1 && y == h-1) {
	return 1;
    }
    int res = 100000000;
    foreach(i;d){
	if(x+i>=w || x+i < 0 ) continue;
	if(used[y][x+i]) continue;
	if(i == -1 && wwall[y][x]) continue;
	if(i != -1 && wwall[y][x+i]) continue;
	res = min(res,1 + saiki(x+i,y,used));
    }
    foreach(i;d){
	if(y+i>=h || y+i < 0 ) continue;
	if(used[y+i][x]) continue;
	if(i == -1 && hwall[y][x]) continue;
	if(i != -1 && hwall[y+i][x]) continue;
	res = min(res,1 + saiki(x,y+i,used));
    }
    return dp[y][x] = res;
}

void main(){

    while(true){
	int[][] th,tw;
	bool[31][31] u;
	dp = new int[31][31];
	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();
	int ans = saiki(0,0,u);
	if(ans >= 100000000) ans = 0;
	writeln(ans);
    }

}