//DFS深度优先搜索,WA了5次就因为1个while后面的条件差了一个……教训啊!!! #include<iostream> using namespace std; int map[22][22],possible,minstep,w,h,beginx,beginy; void dfs(int x,int y,int r,int di)//di是4个方向的编号 1:向上 2:向右 3:向下 4:向左 { if(r > minstep) return;//剪枝,超过最少步数的深搜无效返回 if(di == 1) { if(map[y-1][x] == -1||map[y-1][x] == 1) return; while(map[y-1][x] == 0||map[y-1][x] == 3) { if(map[y-1][x] == 3) { possible = 1; if(r < minstep) minstep = r; return; } y--; if(map[y-1][x] == -1) return; if(map[y-1][x] == 1) { map[y-1][x] = 0; break; } } dfs(x,y,r+1,1); dfs(x,y,r+1,2); dfs(x,y,r+1,3); dfs(x,y,r+1,4); map[y-1][x] = 1;//很关键!一定要改回来!注意DFS的出口处恢复被修改过的值 } else if(di == 2) { if(map[y][x+1] == -1||map[y][x+1] == 1) return; while(map[y][x+1] == 0||map[y][x+1] == 3) { if(map[y][x+1] == 3) { possible = 1; if(r < minstep) minstep = r; return; } x++; if(map[y][x+1] == -1) return; if(map[y][x+1] == 1) { map[y][x+1] = 0; break; } } dfs(x,y,r+1,1); dfs(x,y,r+1,2); dfs(x,y,r+1,3); dfs(x,y,r+1,4); map[y][x+1] = 1; } else if(di == 3) { if(map[y+1][x] == -1||map[y+1][x] == 1) return; while(map[y+1][x] == 0||map[y+1][x] == 3) { if(map[y+1][x] == 3) { possible = 1; if(r < minstep) minstep = r; return; } y++; if(map[y+1][x] == -1) return; if(map[y+1][x] == 1) { map[y+1][x] = 0; break; } } dfs(x,y,r+1,1); dfs(x,y,r+1,2); dfs(x,y,r+1,3); dfs(x,y,r+1,4); map[y+1][x] = 1; } else if(di == 4) { if(map[y][x-1] == -1||map[y][x-1] == 1) return; while(map[y][x-1] == 0||map[y][x-1] == 3) { if(map[y][x-1] == 3) { possible = 1; if(r < minstep) minstep = r; return; } x--; if(map[y][x-1] == -1) return; if(map[y][x-1] == 1) { map[y][x-1] = 0; break; } } dfs(x,y,r+1,1); dfs(x,y,r+1,2); dfs(x,y,r+1,3); dfs(x,y,r+1,4); map[y][x-1] = 1; } } int main() { while(cin >> w >> h) { if(w == 0) break; memset(map,-1,sizeof(map)); possible = 0; minstep = 10; for(int i = 1; i <= h;++i) for(int j = 1;j <= w;++j) { cin >> map[i][j]; if(map[i][j] == 2) { map[i][j] = 0; beginx = j; beginy = i; } } //从起点开始向4个方向深搜 dfs(beginx,beginy,1,1); dfs(beginx,beginy,1,2); dfs(beginx,beginy,1,3); dfs(beginx,beginy,1,4); if(possible) cout << minstep << endl; else cout << -1 << endl; } return 0; }