SERGRID - Grid
You are on an nxm grid where each square on the grid has a digit on it. From a given square that has digit k on it, a Move consists of jumping exactly k squares in one of the four cardinal directions. A move cannot go beyond the edges of the grid; it does not wrap. What is the minimum number of moves required to get from the top-left corner to the bottom-right corner?
Input
Each input will consist of a single test case. Note that your program may be run multiple times on different inputs. The first line of input contains two space-separated integers n and m (1≤n,m≤500), indicating the size of the grid. It is guaranteed that at least one of n and m is greater than 1. The next n lines will each consist of m digits, with no spaces, indicating the nxm grid. Each digit is between 0 and 9, inclusive. The top-left corner of the grid will be the square corresponding to the first character in the first line of the test case. The bottom-right corner of the grid will be the square corresponding to the last character in the last line of the test case.
Output
Output a single integer on a line by itself representing the minimum number of moves required to get from the top-left corner of the grid to the bottom-right. If it isn’t possible, output -1.
Example
Input: 5 4 2120 1203 3113 1120 1110
Output: 6
思路:恰好能够跳Map[i][j]步,dfs超时,改用bfs
代码:
#include<iostream>
#include<string>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<queue>
#include<algorithm>
using namespace std;
const int INF=0X3F3F3F3F;
const int MAXN=550;
int Map[MAXN][MAXN];
bool vis[MAXN][MAXN];
int n,m;
struct node
{
int x,y,step;
node(){x=y=step=0;}
};
void init()
{
memset(Map,0,sizeof(Map));
memset(vis,false,sizeof(vis));
char s[m+2];
for(int i=0;i<n;i++)
{
scanf("%s",s);
for(int j=0;j<m;j++)Map[i][j]=s[j]-'0';
}
}
int bfs()
{
node now,next;
queue<node> q;
now.x=now.y=now.step=0;
vis[0][0]=true;
q.push(now);
while(!q.empty())
{
now=q.front();q.pop();
if(now.x==n-1&&now.y==m-1)return now.step;
int dir[4][2]={{0,Map[now.x][now.y]},{0,-Map[now.x][now.y]},{Map[now.x][now.y],0},{-Map[now.x][now.y],0}};
for(int i=0;i<4;i++)
{
int xx=now.x+dir[i][0],yy=now.y+dir[i][1];
if(xx<0||xx>=n||yy<0||yy>=m)continue;
if(vis[xx][yy])continue;
next.x=xx;next.y=yy;next.step=now.step+1;
vis[next.x][next.y]=true;
q.push(next);
}
}
return -1;
}
int main()
{
while(~scanf("%d %d\n",&n,&m))
{
init();
int result=bfs();
printf("%d\n",result);
}
return 0;
}