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
题意:每次只能走四方方向之一(上下左右),每次走的步数是当前所在位置上的数值,从左上角到右下角求最短需要几步,不能则输出-1。
求最少步数,用bfs,这里注意开一个二维数组vis[i][j]代表从(0,0)到(i,j)经历了几步!!!
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 500 + 7;
int vis[MAXN][MAXN];
char gra[MAXN][MAXN];
int n, m, cnt;
int dx[] = {0, -1, 0, 1};
int dy[] = {1, 0, -1, 0};
struct Point {
Point(int a, int b, int c) : x(a) , y(b) , val(c) {};
int x, y, val;
};
bool isValid(int x, int y) {
return x >= 0 && x < n && y >= 0 && y < m;
}
bool bfs(int x, int y, int c) {
memset(vis, 0, sizeof(vis));
queue<Point> q;
q.push(Point(x, y, c));
while(!q.empty()) {
Point P = q.front();
q.pop();
for (int i = 0; i < 4; ++i)
{
int _x = P.x + dx[i]*P.val;
int _y = P.y + dy[i]*P.val;
if (isValid(_x, _y) && !vis[_x][_y])
{
Point vertex(_x, _y, gra[_x][_y]-'0');
q.push(vertex);
vis[_x][_y] += (vis[P.x][P.y] + 1);
if(_x == n-1 && _y == m-1) {
return true;
}
}
}
}
return false;
}
int main() {
ios::sync_with_stdio(false);
while(cin >> n >> m) {
for(int i = 0; i < n; ++i) {
cin >> gra[i];
}
if(bfs(0, 0, gra[0][0]-'0')) {
cout << vis[n-1][m-1] << endl;
}
else {
cout << -1 << endl;
}
}
return 0;
}