题目地址:http://codeforces.com/gym/100819/attachments
题目:
You are on the top left square of an m × n 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 ofthe four cardinal directions. What is the minimum number of moves required to get from the topleft corner to the bottom right corner?
Input
The first line of input contains two space-separated positive integers m and n (1 ≤ m, n ≤ 500). Itis guaranteed that at least one of m and n is greater than 1. The next m lines each consists of ndigits, describing the m × n grid. Each digit is between 0 and 9.
Output
Print, on a single line, a single integer denoting the minimum number of moves needed to get fromthe top-left corner to the bottom-right corner. If it is impossible to reach the bottom-right corner,print IMPOSSIBLE instead.
思路:
bfs。走的路是格子里的数值。
代码:
#include<iostream>
#include<queue>
using namespace std;
char maze[505][505];
int d[505][505];
int m,n;
const int INF=10000000;
typedef pair<int,int> P;
int k;
void bfs(int x,int y)
{
queue<P> q;
q.push(P(0,0));
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
d[i][j]=INF;
}
}
d[0][0]=0;
while(q.size())
{
P p=q.front();q.pop();
if(p.first==m-1&&p.second==n-1){k=1;break;}
int dx[4] = { 0,0,-(maze[p.first][p.second] - 48),(maze[p.first][p.second] - 48) };
int dy[4] = { -(maze[p.first][p.second] - 48),(maze[p.first][p.second] - 48),0,0 };
for(int i=0;i<4;i++)
{
int nx=p.first+dx[i],ny=p.second+dy[i];
if(nx>=0&&nx<m&&ny>=0&&ny<n&&d[nx][ny]==INF)
{
q.push(P(nx,ny));
d[nx][ny]=d[p.first][p.second]+1;
}
}
}
if(k==1)cout<<d[m-1][n-1]<<endl;
else cout<<"IMPOSSIBLE"<<endl;
}
int main()
{
cin>>m>>n;
k=0;
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
cin>>maze[i][j];
}
}
bfs(0,0);
return 0;
}