上海计算机学会2024年4月月赛C++丙组T5数字迷宫
发布时间
阅读量:
阅读量
数字迷宫
内存限制: 256 Mb时间限制: 1000 ms
题目描述
给定一个 n×m 的网格数字迷宫,每个网格上有一个数字,第 i 行、第 j 列网格上的数字为 a(i,j) ,表示走到这个格子后,下一次移动可以往上下左右任一方向走 a(i,j) 格。
请问,若从网格左上角 (1,1) 位置走到右下角 (n,m) 位置,最少需要走多少次?
输入格式
输入第一行,两个正整数分别表示 n,m
接下来的第 2 行至第 n+1 行,每行 m 个数字,用空格隔开,其中第 i+1 行、第 j 列的数字表示 a(i,j) 。
输出格式
输出一个整数,表示最少步数,若无法达到右下角,则输出 No Solution
数据范围
- 对于 30%的数据,1≤n,m≤10
- 对于 60%的数据,1≤n,m≤100
- 对于 100%的数据,1≤n,m≤10^3,1≤ai≤max(n,m)
样例数据
输入:
3 4
1 2 3 4
1 1 1 1
2 2 2 2
输出:
3
说明:
(1,1)-->(1,2)-->(3,2)-->(3,4)
解析:标准广度优先搜索,只是移动距离做了变化,详见代码:
#include <bits/stdc++.h>
using namespace std;
struct node {
int x,y,step;
};
queue <node>q;
int n,m;
int a[1005][1005];
bool vis[1005][1005];
int dx[4]={0,0,1,-1};
int dy[4]={1,-1,0,0};
void bfs(){
vis[1][1]=1;
node t={1,1,0};
q.push(t);
while (!q.empty()){
t=q.front();
q.pop();
int x=t.x;
int y=t.y;
int step=t.step;
if (x==n&&y==m){
cout<<step;
return;
}
for(int i=0;i<4;i++){
int xx=x+dx[i]*a[x][y];
int yy=y+dy[i]*a[x][y];
if (xx>=1&&xx<=n&&yy>=1&&yy<=m&&vis[xx][yy]==0){
vis[xx][yy]=1;
q.push({xx,yy,step+1});
}
}
}
cout<<"No Solution";
return;
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin>>n>>m;
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
cin>>a[i][j];
}
}
bfs();
return 0;
}
AI写代码cpp

全部评论 (0)
还没有任何评论哟~
