搜索题,但是很容易误认为是bfs,由于物体可以沿一个方向持续移动,直到出界或遇到墙。所有每一次移动后可能形成一个新的状态,所以是dfs
#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;
int n,m,a[22][22],si,sj,ei,ej,ans;
int dx[] = {0,0,1,-1},dy[]={1,-1,0,0};
int isin(int x,int y){
return x>=0&&x<n&&y>=0&&y<m;
}
void dfs(int x,int y,int step){
if(step>ans) return ;
for(int i = 0 ;i<4;i++){
int nx = x + dx[i],ny = y + dy[i];
while(isin(nx,ny)&&a[nx][ny] != 1){
if(nx == ei && ny == ej) {
ans = min(ans,step+1);
return ;
}
nx += dx[i];
ny += dy[i];
}
if(nx == x + dx[i] && ny == y+dy[i]) continue;
if(isin(nx,ny)&&a[nx][ny] ==1){
a[nx][ny] = 0;
dfs(nx-dx[i],ny-dy[i],step+1);
a[nx][ny] = 1;
}
}
}
int main(){
while(scanf("%d%d",&m,&n)&&m+n){
ans = 11;
for(int i = 0;i<n;i++)
for(int j = 0;j<m;j++){
scanf("%d",&a[i][j]);
if(a[i][j] == 2) si = i,sj = j;
else if(a[i][j] == 3) ei = i,ej = j;
}
dfs(si,sj,0);
if(ans == 11 ) printf("-1\n");
else printf("%d\n",ans);
}
return 0;
}