#include #include #include #include using namespace std; struct Point { int x, y; Point() {} Point(int xx, int yy) : x(xx), y(yy) {} bool operator <(const Point& b) const { if(x == b.x) return y < b.y; return x < b.x; } }; int w, h; int field[10][10]; Point init; multimap up; void SubSearch(int dist, const Point& pos) { bool cache[10][10]; memset(cache, 0, sizeof(cache)); multimap u; u.insert(make_pair(0, pos)); while(!u.empty()) { int d = u.begin()->first; Point p = u.begin()->second; u.erase(u.begin()); int& t = field[p.x][p.y]; if(t == 0 || cache[p.x][p.y]) continue; cache[p.x][p.y] = true; if(t >= 3) up.insert(make_pair(dist+d, p)); if(d == 5) continue; u.insert(make_pair(d+1, Point(p.x+1, p.y))); u.insert(make_pair(d+1, Point(p.x-1, p.y))); u.insert(make_pair(d+1, Point(p.x, p.y+1))); u.insert(make_pair(d+1, Point(p.x, p.y-1))); } } int Search() { set cache; up.clear(); up.insert(make_pair(0, init)); while(!up.empty()) { int d = up.begin()->first; Point p = up.begin()->second; up.erase(up.begin()); if(!cache.insert(p).second) continue; //cout << d << p.x << p.y << endl; int& t = field[p.x][p.y]; if(t == 3) return d; t = 1; SubSearch(d, p); } return -1; } int main() { while(cin >> w >> h && w && h) { memset(field, 0, sizeof(field)); for(int y = 1; y <= h; ++y) for(int x = 1; x <= w; ++x) { cin >> field[x][y]; if(field[x][y] == 2) init = Point(x,y); } cout << Search() << endl; } }