当前位置:网站首页>汉诺塔问题
汉诺塔问题
2022-07-31 01:38:00 【小卢要刷力扣题】
前言
给定一个数组arr,长度为N,arr中的值只有1,2,3三种
arr[i] == 1,代表汉诺塔问题中,从上往下第i个圆盘目前在左
arr[i] == 2,代表汉诺塔问题中,从上往下第i个圆盘目前在中
arr[i] == 3,代表汉诺塔问题中,从上往下第i个圆盘目前在右
那么arr整体就代表汉诺塔游戏过程中的一个状况
如果这个状况不是汉诺塔最优解运动过程中的状况,返回-1
如果这个状况是汉诺塔最优解运动过程中的状况,返回它是第几个状况
解题思路
7层汉诺塔问题的一个状态
最优解的第一个状态
全部盘子都在左边
第二个状态就是1号盘子在右边
第三个状态就是2号盘子在中间
i: 1~i的圆盘需要移动
F: 1~i的圆盘现在处在什么圆盘上,可能是左中右.
t:需要去的位置可能是左,中,右
other:除了from, to的另外一个位置
i层的圆盘没有任何道理是在other.上
如果index还在From上,说明第一大步没走完
第一步:1~i-1 从from到other
第二步:i从from到to
第三步:1~i-1从other到to
把每一步都用递归分解
最后相加,得出为第几步
代码
public static int kth(int[] arr) {
int N = arr.length;
return step(arr, N - 1, 1, 3, 2);
}
// 0...index这些圆盘,arr[0..index] index+1层塔
// 在哪?from 去哪?to 另一个是啥?other
// arr[0..index]这些状态,是index+1层汉诺塔问题的,最优解第几步
public static int step(int[] arr, int index, int from, int to, int other) {
if (index == -1) {
return 0;
}
if (arr[index] == other) {
return -1;
}
// arr[index] == from arr[index] == to;
if (arr[index] == from) {
return step(arr, index - 1, from, other, to);
} else {
int p1 = (1 << index) - 1;
int p2 = 1;
int p3 = step(arr, index - 1, other, to, from);
if (p3 == -1) {
return -1;
}
return p1 + p2 + p3;
}
}
边栏推荐
猜你喜欢
ROS Action communication
进程间通信学习笔记
1782. Count the number of point pairs Double pointer
孩子的编程启蒙好伙伴,自己动手打造小世界,长毛象教育AI百变编程积木套件上手
软件测试要达到一个什么水平才能找到一份9K的工作?
GCC Rust获批将被纳入主线代码库,或将于GCC 13中与大家见面
倍增、DFS序
九州云入选“可信云最新评估体系及2022年通过评估企业名单”
内网渗透——提权
What have I experienced when I won the offer of BAT and TMD technical experts?
随机推荐
《云原生的本手、妙手和俗手》——2022全国新高考I卷作文
TiDB 操作实践 -- 备份与恢复
.NET 跨平台应用开发动手教程 |用 Uno Platform 构建一个 Kanban-style Todo App
case语句的综合结果,你究竟会了吗?【Verilog高级教程】
pycharm重命名后无法运行(报错: can‘t open file......No such file or directory)
The difference between 4G communication module CAT1 and CAT4
关于Redis相关内容的基础学习
Xiaohei's leetcode journey: 117. Fill the next right node pointer of each node II
leetcode-399:除法求值
MySQL installation tutorial (detailed, package teaching package~)
24. Please talk about the advantages and disadvantages of the singleton pattern, precautions, usage scenarios
Jiuzhou Cloud was selected into the "Trusted Cloud's Latest Evaluation System and the List of Enterprises Passing the Evaluation in 2022"
pc端判断当前使用浏览器类型
Basic Parameters of RF Devices 2
link与@import的区别
TiDB之rawkv升级之路v5.0.4--&gt;v6.1.0
MySQL的存储过程
leetcode-1161:最大层内元素和
数字图像隐写术之卡方分布
kotlin中函数作为参数和函数作为返回值实例练习