import std.stdio;
import std.algorithm;
import std.string;
import std.range;
import std.array;
import std.conv;
import std.complex;
import std.math;
import std.ascii;
import std.bigint;
import std.container;
import std.typecons;

auto readInts() {
	return array(map!(to!int)(readln().strip().split()));
}
auto readInt() {
	return readInts()[0];
}
auto readLongs() {
	return array(map!(to!long)(readln().strip().split()));
}
auto readLong() {
	return readLongs()[0];
}

const real eps = 1e-10;

void calc(int[][] m, int x, int y,int[][] cost, int c) {
	if(cost[x][y] <= c) {
		return;
	}
	cost[x][y] = c;
	if(m[2*x][y] == 0) {
		calc(m, x-1, y, cost, c+1);
	}
	if(m[2*x+2][y] == 0) {
		calc(m, x+1, y, cost, c+1);
	}
	if(m[2*x+1][y] == 0) {
		calc(m, x, y-1, cost, c+1);
	}
	if(m[2*x+1][y+1] == 0) {
		calc(m, x, y+1, cost, c+1);
	}
}

void main(){
	while(true) {
		auto wh = readInts();
		auto w = wh[0];
		auto h = wh[1];
		if((w|h) == 0) return;

		int[][] m;
		m ~= new int[](w+1).map!(a => 1).array;
		for(int i; i < 2*h-1; ++i) {
			auto l = readInts();
			if(i%2 == 0) {
				l = 1 ~ l ~ 1;
			}
			m ~= l;
		}
		m ~= new int[](w+1).map!(a => 1).array;
		auto cost = new int[][](h,w);
		for(int i; i < h; ++i) {
			for(int j; j < w; ++j) {
				cost[i][j] = int.max;
			}
		}
		calc(m, 0, 0, cost, 1);
		writeln(cost[h-1][w-1] == int.max ? 0: cost[h-1][w-1]);
	}
}