题意:
从左上角跳到右下角最少需要多少步,跳的规则为:可以向四个方向的任意一个方向跳当前格子中的步数,若跳不到右下角输出IMPOSSIBLE。
题解:
BFS搜索,注意判断边界,标记。
代码:
#include <iostream> #include <cstdio> #include <algorithm> #include <stdio.h> #include <cmath> #include <cstring> #include <vector> #include <map> #include <set> #include <bitset> #include <queue> #include <cstdlib> #include <utility> using namespace std; #define is_lower(c) (c>='a' && c<='z') #define is_upper(c) (c>='A' && c<='Z') #define is_alpha(c) (is_lower(c) || is_upper(c)) #define is_digit(c) (c>='0' && c<='9') #define min(a,b) ((a)<(b)?(a):(b)) #define max(a,b) ((a)>(b)?(a):(b)) #define IO ios::sync_with_stdio(0);\ cin.tie();\ cout.tie(); #define For(i,a,b) for(int i = a; i <= b; i++) typedef long long ll; typedef unsigned long long ull; typedef pair<int,int> pii; typedef pair<int,int > pll; typedef vector<int> vi; const ll inf=0x3f3f3f3f; ; const ll inf_ll=(ll)1e18; const ll maxn=100005LL; const ll mod=1000000007LL; +; pair <int,int> p; queue <pii> q; int mp[N][N]; int xx[N][N]; bool vis[N][N]; int main() { int m,n; cin >> m >> n; For(i,,m) For(j,,n) scanf("%1d",&mp[i][j]); p.first = ;p.second = ; q.push(p); vis[][] = ; ; while(!q.empty()){ pii x = q.front(); q.pop(); int step = mp[x.first][x.second]; pii x1; &&(x.first+step)<=m&&!vis[x.first+step][x.second]){ x1.first = x.first+step,x1.second = x.second; q.push(x1); xx[x1.first][x1.second] = xx[x.first][x.second]+; vis[x1.first][x1.second] = ; }//向下 &&(x.first-step)<=m&&!vis[x.first-step][x.second]){ x1.first = x.first-step,x1.second = x.second; q.push(x1); xx[x1.first][x1.second] = xx[x.first][x.second]+; vis[x1.first][x1.second] = ; }// up &&(x.second+step)<=n&&!vis[x.first][x.second+step]){ x1.first = x.first,x1.second = x.second+step; q.push(x1); xx[x1.first][x1.second] = xx[x.first][x.second]+; vis[x1.first][x1.second] = ; } &&(x.second-step)<=n&&!vis[x.first][x.second-step]){ x1.first = x.first,x1.second = x.second-step; q.push(x1); xx[x1.first][x1.second] = xx[x.first][x.second]+; vis[x1.first][x1.second] = ; } ) break; } ) cout << xx[m][n] <<endl; else cout <<"IMPOSSIBLE" << endl; ; }