当前位置:网站首页>迷宫问题----经典回溯法解决
迷宫问题----经典回溯法解决
2022-07-30 05:46:00 【RSDYS】
问题描述:
题目摘自尚硅谷,小球在红色范围内运动,从规定的位置按照一定的运动规则到达指定位置,即可完成迷宫。
算法思路:
因为地图和挡板需要我们自己设置,所以先填充地图,运用二维数组对地图进行填充,我们设置1为墙体,2为小球走过的地方,还可以设置3为小球无法通过的地方,在此之后,我们还要对小球设置一个运动规则,比如说我们设置小球先向下运动,如果不行的话,再向右运动,如果还不行的话,向上运动,最后再向左运动,通过这个规则我们可以控制小球的回溯。
当进入回溯函数时,首先设置出口,当碰到墙体和刚刚走过的路时,会返回false值,当走到终点时,返回true值。
代码:
/回溯迷宫问题
public class MiGong {
static int map[][] = new int[8][7];
//设置迷宫数组
public static void main(String[] args) {
for(int i = 0; i < 7; i++){
map[0][i] = 1;
map[7][i] = 1;
}
for(int i = 0; i < 8; i++){
map[i][0] = 1;
map[i][6] = 1;
}
map[3][1] = 1;
map[3][2] = 1;
//设置完迷宫的墙体和挡板
System.out.println("地图预览");
print();
if(recu(map,1,1)){
System.out.println("闯关成功");
print();
}
}
private static boolean recu(int map[][],int i, int j){
if(map[i][j] == 1 || map[i][j] == 2) //当碰到墙体和已经走过的地方时,返回false值
{
return false;
}
if(i == 6 && j == 5 ){ //当走到最后一块时,闯关成功
map[i][j] = 2;
return true;
}
map[i][j] = 2; //走过的地方标记为2
if(recu(map,i+1,j) || recu(map,i,j+1) || recu(map,i-1,j) || recu(map, i,j-1)) //进行按照一定运动规则进行运动
return true;
return false;
}
//打印地图
private static void print(){
for(int i = 0; i < 8; i++){
for(int j = 0; j < 7; j++){
System.out.print(map[i][j]+" ");
}
System.out.println();
}
}
}
边栏推荐
- clinit方法
- 顺序二叉树---实现数组的二叉树前序遍历输出
- 【已解决:el-input标签无法输入或不显示文字】
- -----博客声明
- C language, usage of qsort in library function, and explanation
- Acwing Brush Questions Section 1
- Diwen serial screen production (serialization 1) ===== preparation work
- 闭包(你不知道的JS)
- [Punctuality Atom] Simple application of sys.c, sys.h bit-band operations
- antd table Summary总结栏置顶
猜你喜欢
给Vscode配置ESlint语法检查 — ESLint 插件自动格式化设置(实现Ctrl+S 按照ESLint规则自动格式化代码)
QT每周技巧(2)~~~~~~~~~界面按钮
主机和从机配置,建立ssh连接实现Rviz远程控制
C语言,库函数中qsort的用法,及解释
QT serial port dynamically displays a large number of data waveform curves in real time (5) ======== "Final perfect solution version"
多层板的层数,为啥选项都是偶数?就不能选奇数?
三种内核结构---宏内核、微内核、混合内核
无法完成包的安装npm ERR! Refusing to install package with name “moment“ under a package also called “moment“
查看 word版本号
QT Weekly Skills (1) ~~~~~~~~~ Running Icon
随机推荐
Word使用中常用的快捷键
基于QT的CAN通讯数据实时波形显示(连载八)====“子函数或新类调用ui控件”
QT每周技巧(1)~~~~~~~~~运行图标
pdf和word等文档添加水印
Deep Interpretation of void (*signal(int , void(*)(int)))(int) in "C Traps and Defects"
xxx is not in the sudoers file.This incident will be reported错误
【江科大自化协stm32F103c8t6】笔记之【入门32单片机及EXTI外部中断初始化参数配置】
VsCode与Sublime编辑器优缺点对比
昆仑通态屏幕制作(连载1)---接触篇
openssl 1.1.1 compile statement
Cannnot download sources不能下载源码百分百超详细解决方案
华秋电子成为开放原子开源基金会openDACS捐赠人,共建 openDACS开源生态
[Punctuality Atom] Simple application of sys.c, sys.h bit-band operations
QT weekly skills (3)~~~~~~~~~ serial port addition
Written before the official account - QT, ARM, DSP, microcontroller, power electronics and transmission!
[Common usage of markdown]
2021年软考中级过关
About map custom sorting of keys
暂时存着阿里云
Acwing刷题第一节