#include #include #include int width, height; int table[7][7]; const int UP = 1, DOWN = 2, LEFT = 3, RIGHT = 4; struct State{ int sch_x, sch_y, cargo_x, cargo_y; int count; State(int a, int b, int c, int d): sch_x(a), sch_y(b), cargo_x(c), cargo_y(d), count(0){} bool operator < (const State & s) const { if(sch_x != s.sch_x){return sch_x < s.sch_x;} if(sch_y != s.sch_y){return sch_y < s.sch_y;} if(cargo_x != s.cargo_x){return cargo_x < s.cargo_x;} if(cargo_y != s.cargo_y){return cargo_y < s.cargo_y;} return false; } }; struct less2{ bool operator () (const State & s, const State & t) { if(s.count != t.count){return s.count < t.count;} return s < t; } }; bool out_of_range(int x, int y){ if(x < 0 || y < 0 || x >= width || y >= height){return true;} return table[y][x] == 1; } bool canGo(const State & s, int direction, State * newState){ int dxs[] = {0, 0, 0, -1, 1}; int dys[] = {0, -1, 1, 0, 0}; int dx = dxs[direction]; int dy = dys[direction]; int cargo_dx = 0; int cargo_dy = 0; int dcount = 0; if(out_of_range(dx + s.sch_x, dy + s.sch_y)){ return false; } if(dx + s.sch_x == s.cargo_x && dy + s.sch_y == s.cargo_y){ if(out_of_range(dx * 2 + s.sch_x, dy * 2 + s.sch_y)){ return false; } cargo_dx = dx; cargo_dy = dy; dcount = 1; } if(newState){ newState->sch_x = s.sch_x + dx; newState->sch_y = s.sch_y + dy; newState->cargo_x = s.cargo_x + cargo_dx; newState->cargo_y = s.cargo_y + cargo_dy; newState->count = s.count + dcount; } return true; } int main(){ while(true){ std::cin >> width >> height; if(width == 0 && height == 0){break;} State s(0, 0, 0, 0); for(int i = 0; i < height; i++){ for(int j = 0; j < width; j++){ std::cin >> table[i][j]; if(table[i][j] == 2){ s.cargo_x = j; s.cargo_y = i; } if(table[i][j] == 4){ s.sch_x = j; s.sch_y = i; } } } std::set cache; std::set q; cache.insert(s); q.insert(s); State newState(0, 0, 0, 0); while(!q.empty()){ //std::cout << q.size() << ", " << cache.size() << std::endl; s = *q.begin(); if(table[s.cargo_y][s.cargo_x] == 3){break;} q.erase(q.begin()); for(int direction = 1; direction <= 4; direction++){ if(canGo(s, direction, &newState)){ if(cache.find(newState) == cache.end()){ cache.insert(newState); q.insert(newState); } } } } std::cout << (q.empty() ? (-1): s.count) << std::endl; } }