click me to submit
IN this question , their is a little bit change.first we need to find a far enough location ,than we should go one step further to change the unreachable block reachable , and than take step back to continue.
#include <iostream>
#include <cstring>
#include <cstdio>
#include <vector>
#include <algorithm>
#include <set>
#include <map>
#define rep(i, n) for(i;i<n;i++)
#define inf 0x7f7f7f7f7f
using namespace std;
int b[101][101];
int vis[25][25]; //indicate ith number is marked
int n,m;
int ans =11;
int dx[4] = {0,1,0,-1};
int dy[4] = {1,0,-1,0};
bool check(int x,int y)
{
//cout<<"checking:"<<x<<", "<<y<<endl;
if(x<0||y<0||x>=n||y>=m) return false;
else return true;
}
void dfs(int x,int y,int step)
{
//cout<<x<<" "<<y<<" "<<step<<endl;
if(step>10) return ;
int leap = 0;
int xx,yy;
for(int i=0;i<4;i++)
{
leap = 0;
if(b[x+dx[i]][y+dy[i]] == 1) continue;
xx = x;
yy = y;
while(1)
{
xx += dx[i];
yy += dy[i];
if(!check(xx,yy))
{
leap = 1;
break;
}
if(b[xx][yy] == 1)
{
break;
}
if(b[xx][yy] == 0)
{
continue;
}
if(b[xx][yy] == 3)
{
ans = min(ans,step);
return ;
}
}
if(leap) continue;
b[xx][yy] = 0;
dfs(xx-dx[i],yy-dy[i],step+1);
b[xx][yy] = 1;
}
}
int main()
{
while(~scanf("%d%d",&m,&n))
{
if(!n&&!m) break;
int sx,sy;
ans = 11;
memset(vis,0,sizeof(vis));
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
scanf("%d",&b[i][j]);
if(b[i][j] == 2)
{
sx = i;
sy = j;
b[i][j] = 0;
}
}
}
dfs(sx,sy,0);
if(ans+1<11) printf("%d\n",ans+1);
else printf("-1\n");
}
return 0;
}