Go: package main

import (
	"bufio"
	"container/list"
	"fmt"
	"os"
	"strconv"
	"strings"
)

func main() {
	io := NewIo()
	defer io.Flush()
	for {
		w, h := io.NextInt(), io.NextInt()
		if w == 0 {
			break
		}
		xWall := make([][]int, h)
		yWall := make([][]int, h)
		for i := 0; i < h; i++ {
			xWall[i], yWall[i] = make([]int, w), make([]int, w)
			for j := 0; j < w; j++ {
				xWall[i][j], yWall[i][j] = -1, -1
			}
		}
		for i := 0; i < h*2-1; i++ {
			if i%2 == 0 {
				for j := 0; j < w-1; j++ {
					xWall[i/2][j] = io.NextInt()
				}
			} else {
				for j := 0; j < w; j++ {
					yWall[i/2][j] = io.NextInt()
				}
			}
		}
		//io.Println(bfs(w, h, xWall, yWall))
		fmt.Println(bfs(w, h, xWall, yWall))
	}
}

type P struct {
	x, y int
}

func bfs(w, h int, x, y [][]int) int {
	d := make([][]int, h)
	for i := 0; i < h; i++ {
		d[i] = make([]int, w)
	}
	q := list.New()
	q.PushBack(P{0, 0})
	d[0][0] = 1

	for q.Len() != 0 {
		pos := q.Remove(q.Front()).(P)
		if pos.x == w-1 && pos.y == h-1 {
			break
		}
		if pos.x > 0 && x[pos.y][pos.x-1] == 0 && d[pos.y][pos.x-1] == 0 {
			d[pos.y][pos.x-1] = d[pos.y][pos.x] + 1
			q.PushBack(P{pos.x - 1, pos.y})
		}
		if pos.x < w-1 && x[pos.y][pos.x] == 0 && d[pos.y][pos.x+1] == 0 {
			d[pos.y][pos.x+1] = d[pos.y][pos.x] + 1
			q.PushBack(P{pos.x + 1, pos.y})
		}
		if pos.y > 0 && y[pos.y-1][pos.x] == 0 && d[pos.y-1][pos.x] == 0 {
			d[pos.y-1][pos.x] = d[pos.y][pos.x] + 1
			q.PushBack(P{pos.x, pos.y - 1})
		}
		if pos.y < h-1 && y[pos.y][pos.x] == 0 && d[pos.y+1][pos.x] == 0 {
			d[pos.y+1][pos.x] = d[pos.y][pos.x] + 1
			q.PushBack(P{pos.x, pos.y + 1})
		}
	}
	return d[h-1][w-1]
}

// I/O template
type Io struct {
	reader    *bufio.Reader
	writer    *bufio.Writer
	tokens    []string
	nextToken int
}

func NewIo() *Io {
	return &Io{
		reader: bufio.NewReader(os.Stdin),
		writer: bufio.NewWriter(os.Stdout),
	}
}

func (io *Io) Flush() {
	err := io.writer.Flush()
	if err != nil {
		panic(err)
	}
}

func (io *Io) NextLine() string {
	var buff []byte
	for {
		line, isPrefix, err := io.reader.ReadLine()
		if err != nil {
			panic(err)
		}
		buff = append(buff, line...)
		if !isPrefix {
			break
		}
	}
	return string(buff)
}

func (io *Io) Next() string {
	for io.nextToken >= len(io.tokens) {
		line := io.NextLine()
		io.tokens = strings.Fields(line)
		io.nextToken = 0
	}
	s := io.tokens[io.nextToken]
	io.nextToken++
	return s
}

func (io *Io) NextInt() int {
	i, err := strconv.Atoi(io.Next())
	if err != nil {
		panic(err)
	}
	return i
}

func (io *Io) NextFloat() float64 {
	i, err := strconv.ParseFloat(io.Next(), 64)
	if err != nil {
		panic(err)
	}
	return i
}

func (io *Io) Println(a ...interface{}) {
	fmt.Fprintln(io.writer, a...)
}

func (io *Io) Printf(format string, a ...interface{}) {
	fmt.Fprintf(io.writer, format, a...)
}

func (io *Io) PrintIntSlice(a []int) {
	b := []interface{}{}
	for _, x := range a {
		b = append(b, x)
	}
	io.Println(b...)
}

func (io *Io) PrintStringSlice(a []string) {
	b := []interface{}{}
	for _, x := range a {
		b = append(b, x)
	}
	io.Println(b...)
}

func Log(name string, value interface{}) {
	fmt.Fprintf(os.Stderr, "%s=%+v\n", name, value)
}

func ExampleIo() {
	io := NewIo()
	defer io.Flush()
	a := make([]int, 0, 3)
	a[0], a[1], a[2] = io.NextInt(), io.NextInt(), io.NextInt()
	io.Println(a)
	io.PrintIntSlice(a)
	Log("io", a)
}

C++: 
/*
Problem
 
Category
BFS
 
URL:

 
考察:


Date: 2020/04/21
*/
 
#include <bits/stdc++.h>
using namespace std;
using ll = int64_t;
#define int int64_t


#define INF 1e9

/* ==== Classes ====== */

struct Edge {
    int from, to;
};

class Graph {
    protected:
    vector<int64_t> vlabels;
    vector<vector<int64_t>> elabels;
    vector<vector<int>> AL;
    bool isDirected = true;
    bool hasEdgeLabel = false;
    
    
    public:
    Graph(bool isDirected = true): isDirected(isDirected) {}

    void addNode(int64_t label) {
        vlabels.push_back(label);
        AL.emplace_back();
    }

    void addEdge(int from, int to) {
        AL[from].push_back(to);
        if(!isDirected) {
            AL[to].push_back(from);
        }
    }

    void removeEdge(int from, int to) {
        int deletion = 0;
        for(auto itr = AL[from].begin(); itr != AL[from].end(); ++itr) {
            if (*itr == to) {
                AL[from].erase(itr);
                deletion++;
                break;
            }
        }
        assert(deletion==1); // 削除が起きたかチェック
        if (!isDirected) {
            for(auto itr = AL[to].begin(); itr != AL[to].end(); ++itr) {
                if (*itr == from) {
                    AL[to].erase(itr);
                    deletion++;
                    break;
                }
            }
        }
        assert(deletion==2); // 削除が起きたかチェック
        return;
    }

    void removeDualEdge(int from, int to) {
        int deletion = 0;
        for(auto itr = AL[from].begin(); itr != AL[from].end(); ++itr) {
            if (*itr == to) {
                AL[from].erase(itr);
                deletion++;
                break;
            }
        }
        for(auto itr = AL[to].begin(); itr != AL[to].end(); ++itr) {
            if (*itr == from) {
                AL[to].erase(itr);
                deletion++;
                break;
            }
        }
        assert(deletion==2); // 削除が起きたかチェック
        return;
    }

    void setEdgeLabel(int from, int to, int64_t v) {
        cout<<"elabels を初期化していないので使えません。"<<endl;
        exit(0);
        elabels[from][to] = v;
    }

    int64_t getEdgeLabel(int from, int to) {
        return 1;
    }

    void setLabel(int id, int label) {vlabels[id] = label;}
    int64_t getLabel(int id) { assert(id<vlabels.size()); return vlabels[id]; }
    vector<int> getNeighbors(int id) { return AL[id]; }
    
    void show() {
        cout<<"======= info ======="<<endl;
        cout<<"|V|: "<<vlabels.size()<<endl;
        int cnt=0; for (auto al: AL) cnt+=al.size();
        cout<<"|E|: "<<cnt<<endl;
        cout<<"======="<<endl;
        for(int i=0; i<vlabels.size(); ++i) {
            cout<<i<<" ("<<vlabels[i]<<"): ";
            for (int j=0; j<AL[i].size(); ++j) {
                cout<<AL[i][j];
                if (j != AL[i].size()-1) cout<<", ";
            }
            cout<<endl;
        }
        return;
    }

    int getDistance(int from, int to) {
        if (!hasEdgeLabel) {
            return getDistanceByBFS(from, to);
        }
        else{
            cout<<"sorry, not supported"<<endl;
            exit(0);
        }
    }

    int size() {return vlabels.size();}

    private:
    
    int getDistanceByBFS(int from, int to) {
        // set<int> searchedNodes;
        vector<int64_t> distanceMap(size(), INF);
        distanceMap[from] = 0;
        queue<int> operations;
        operations.push(from);
        while(!operations.empty()) {
            auto op = operations.front();
            int f = op;
            int d = distanceMap[f];
            operations.pop();
            auto neighbors = getNeighbors(f);
            for(auto nb: neighbors) {
                if (distanceMap[nb] > d + 1) {
                    distanceMap[nb] = d+1;
                    operations.push(nb);
                }
            }
        }
        return distanceMap[to];
    }

};

class GridGraph : public Graph {
    protected:
    int H, W;
    public:
    GridGraph(int H, int W, int label=0): Graph(), H(H), W(W){
        vlabels = vector<int64_t>(H*W, label);
        AL = vector<vector<int>>(H*W, vector<int>());
        vector<int> dh = {1, 0, -1, 0};
        vector<int> dw = {0, 1, 0, -1};
        for(int h=0; h<H; ++h) {
            for(int w=0; w<W; ++w) {
                int from = getIndex({h, w});
                for(int i=0; i < 4; ++i) {
                    int nh = h + dh[i];
                    int nw = w + dw[i];
                    if (nh < 0 or nw < 0 or nh >= H or nw >= W) continue;
                    int to = getIndex({nh, nw});
                    Graph::addEdge(from, to);
                }
            }
        }
    }
    int getIndex(pair<int, int> pos) {
        assert(pos.first <H and pos.second < W and pos.first >=0 and pos.second >=0);
        return pos.first * W + pos.second;
    }
    void addEdge(pair<int, int> from, pair<int, int> to) { Graph::addEdge(getIndex(from), getIndex(to)); }
    void setLabel(pair<int, int> pos, int label) { Graph::setLabel(getIndex(pos), label); }
    int64_t getLabel(pair<int, int> pos, int label) { return Graph::getLabel(getIndex(pos)); }
    void removeEdge(pair<int, int> from, pair<int, int> to) { Graph::removeEdge(getIndex(from), getIndex(to)); }
    void removeDualEdge(pair<int, int> from, pair<int, int> to) { Graph::removeDualEdge(getIndex(from), getIndex(to)); }
    vector<int> getNeighbors(pair<int, int> from) { return AL[getIndex(from)]; }
};


 
/* ==== Declarations ====== */
// functions
void solve();
void getInput();
 
// Global variables
int W, H;
GridGraph GG(0, 0, 0);

/* ======================== */
void getInput() {
    cin>>W>>H;
    if(!W) exit(0);
    GG = GridGraph(H, W, 0);
    for(int i=0; i<2*H -1; ++i) {
        char c;
        if (i%2==0) {
            int h = i/2;
            for(int j=0; j<W-1; ++j) {
                cin>>c;
                if (c=='0')continue;
                pair<int, int> from = {h, j};
                pair<int, int> to = {h, j+1};
                GG.removeDualEdge(from, to);
            }
        } else {
            int h = i/2;
            for(int j=0; j<W; ++j) {
                cin>>c;
                if (c=='0')continue;
                if (h==H-1) continue;
                GG.removeDualEdge({h, j}, {h+1, j});
            }
        }
    }

}
 
 
void solve() {
    auto d = GG.getDistance(0, W*H-1);
    if (d==INF) d=-1;
    cout<<d+1<<endl;
    
}
 
 
 
signed main(){
    while(true){
        getInput();
        solve();
        getInput();
        solve();
        getInput();
        solve();
    }
    return 0;
}