原题链接:信息学奥赛一本通T1255-迷宫问题
解题思路:DFS深搜 + 剪枝
注意事项:移动的顺序, 下右上左
参考代码:
#include<iostream>
#include<string>
#include<sstream>
#include<cstring>
using namespace std;
const int N = 1e1 + 10;
int g[N][N],dis[N][N],mx= 0x3f3f3f3f;
int d[4][2] = {{1,0},{0,1},{-1,0},{0,-1}};
bool v[N][N];
string m_path;
void dfs(int x, int y, string path, int lth){
if(x == 4 && y == 4){
if(mx > lth) {
m_path = path;
mx = lth;
}
return;
}
if(dis[x][y] > lth) dis[x][y] = lth;
else return;
for(int i = 0 ; i < 4; i ++){
int nx = d[i][0] + x;
int ny = d[i][1] + y;
if(nx >= 0 && nx < 5 && ny >=0 && ny < 5 && !g[nx][ny] && !v[nx][ny]){
v[nx][ny] = true;
stringstream ss;
ss << path << "\n(" <<nx <<", "<<ny<<")";
dfs(nx,ny,ss.str(),lth + 1);
v[nx][ny] = false;
}
}
}
int main()
{
memset(dis, 0x3f, sizeof(dis));
for(int i = 0; i < 5; i ++)
for(int j = 0; j < 5; j ++)
cin >> g[i][j];
string s = "(0, 0)";
dfs(0,0,s,0);
cout << m_path;
return 0;
}0.0分
1 人评分
C语言网提供由在职研发工程师或ACM蓝桥杯竞赛优秀选手录制的视频教程,并配有习题和答疑,点击了解:
一点编程也不会写的:零基础C语言学练课程
解决困扰你多年的C语言疑难杂症特性的C语言进阶课程
从零到写出一个爬虫的Python编程课程
只会语法写不出代码?手把手带你写100个编程真题的编程百练课程
信息学奥赛或C++选手的 必学C++课程
蓝桥杯ACM、信息学奥赛的必学课程:算法竞赛课入门课程
手把手讲解近五年真题的蓝桥杯辅导课程
发表评论 取消回复