// Help!!!!!!!zju 1671 为何Wa???
http://acm.zju.edu.cn/show_problem.php?pid=1671
//-------------代码如下--------------------------------
//#include "stdafx.h"
#include <iostream>
#include <queue>
using namespace std;
struct node 
{
    int x, y;
    int energy;
    node(){energy = 0;}
    node(int a, int b, int e){x = a, y = b;energy = e;}
};
int N, M, counter;          // N行M列.
int Map[10][10];
int X[] = {1, -1, 0, 0};
int Y[] = {0, 0, 1, -1};
node Beg, End, Flag, Last;
queue<node> myqueue;
bool B[10][10], Find;       //Find 记录是否找到
void Init()
{
    for(int i = 0; i < N; i++)
        for(int j = 0; j < M; j++)
        {
            cin >> Map[i][j];
            if(Map[i][j] == 2) 
                Beg.x = i, Beg.y = j;
            if(Map[i][j] == 3)
                End.x = i, End.y = j;
        }
    counter = 0;Beg.energy = 6;
    Last = Flag;                    //前一点初始化为标志节点
    Find = true;
    memset(B, true, sizeof(B));
    while(!myqueue.empty()) myqueue.pop();
    myqueue.push(Beg);               //出发点入列
    myqueue.push(Flag);              //标志入列;
}
bool valid_flag(node n)              //判断一层是否遍历完。
{
    return (n.x == Flag.x && n.y == Flag.y);
}
void recover()                      //  补充了食物就将全部HP点恢复。
{
    int i, j;
    for(i = 0; i < N; i++)
        for(j = 0; j < M; j++)
            if(Map[i][j] == 1) B[i][j] = true;
}
void Bfs()
{
    node n = myqueue.front();
    if(Map[n.x][n.y] == 4) recover();      // 补充了食物就将全部HP点恢复。
    if(n.x == Last.x && n.y == Last.y) return ;   // 判断是否剩最后一点Flag
    else Last.x = n.x , Last.y = n.y;             // Last 置为当前节点
    if(Map[n.x][n.y] == 3)                 //判断是否找到终点
        {Find = false; cout << counter << endl;return;} 
    else if(valid_flag(n))                 // 一层结束,记数器加一
        {myqueue.push(Flag); counter ++;}  
    else if(n.energy > 1)                  // 对周围可能走的情况进行处理
    {
        n.energy --;
        for(int i = 0; i < 4; i++)
        {
            node t(n.x + X[i], n.y + Y[i], n.energy);    
            if(t.x >= 0 && t.x < N && t.y >= 0 && t.y < M && B[t.x][t.y])
            {
                B[t.x][t.y] = false;
                if(Map[t.x][t.y] == 1 || Map[t.x][t.y] == 3) myqueue.push(t);
                else if(Map[t.x][t.y] == 4)   myqueue.push(node(t.x, t.y, 6));  
            }
        }
    }
    myqueue.pop();
    Bfs();
}
int main()
{
    Flag.x = -1, Flag.y = -1;
    while(cin >> M >> N, M > 0, N > 0)
    {
        Init();               //初始化
        Bfs();                //广搜
        if(Find) cout << -1 << endl;   //未找到
    }
    return 0;
}



 
											





 
	    

 
	