思路:
在一个方向上走K步,基础BFS。
注意标记;
注意路径;
PS:显著注释是记录路径。
#include<bits/stdc++.h>
using namespace std;
const int N=5e2+10;
char ma[N][N];
bool vis[N][N];
int dx[4]={0,0,-1,1};
int dy[4]={1,-1,0,0};
/***************/
//int prex[N][N];
//int prey[N][N];
/***************/
struct asd{
int x,y;
int step;
};
int n,m;
int BFS()
{
asd now,nex;
queue<asd>q;
memset(vis,false,sizeof(vis));
now.x=0;
now.y=0;
now.step=0;
/********************/
//prex[0][0]=-1;
//prey[0][0]=-1;
/********************/
vis[0][0]=true;
q.push(now);
while(!q.empty())
{
now=q.front();q.pop();
int st=ma[now.x][now.y]-'0';
if(now.x==n-1&&now.y==m-1)
return now.step;
for(int i=0;i<4;i++)
{
int x=now.x+dx[i]*st;
int y=now.y+dy[i]*st;
if(x<0||y<0||x>=n||y>=m||vis[x][y]||(x==now.x&&y==now.y))
continue;
nex.x=x;
nex.y=y;
/******************/
//prex[x][y]=now.x;
//prey[x][y]=now.y;
/******************/
vis[x][y]=true;
nex.step=now.step+1;
q.push(nex);
}
}
return -1;
}
int main()
{
scanf("%d%d",&n,&m);
for(int i=0;i<n;i++)
scanf("%s",ma[i]);
printf("%d\n",BFS());
/*****************/
//int x=n-1,xx;
//int y=m-1,yy;
//while(x!=-1&&y!=-1)
//{
// printf("%d %d\n",x,y);
// xx=prex[x][y];
// yy=prey[x][y];
// x=xx;y=yy;
//}
/******************/
return 0;
}