当前位置:网站首页>Tower of Hanoi problem
Tower of Hanoi problem
2022-07-31 01:48:00 【Xiao Lu wants to brush the force and deduct the question】
前言
给定一个数组arr,长度为N,arr中的值只有1,2,3三种
arr[i] == 1,代表汉诺塔问题中,从上往下第i个圆盘目前在左
arr[i] == 2,代表汉诺塔问题中,从上往下第i个圆盘目前在中
arr[i] == 3,代表汉诺塔问题中,从上往下第i个圆盘目前在右
那么arr整体就代表汉诺塔游戏过程中的一个状况
如果这个状况不是汉诺塔最优解运动过程中的状况,返回-1
如果这个状况是汉诺塔最优解运动过程中的状况,返回它是第几个状况
解题思路
7A state of the Layer Tower of Hanoi problem
The first state of the optimal solution
All plates are on the left
The second state is1Plate No. is on the right
The third state is2The plate is in the middle
i: 1~iThe disc needs to be moved
F: 1~iOn what disk is the disk of ,Possibly left-center-right.
t:The place to go may be left,中,右
other:除了from, toanother location
iThe layer of the disc doesn't make any sense at allother.上
如果index还在From上,Explain that the first big step is not over
第一步:1~i-1 从from到other
第二步:i从from到to
第三步:1~i-1从other到to
Break down each step with recursion
最后相加,get the first step
代码
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;
}
}
边栏推荐
猜你喜欢
斩获BAT、TMD技术专家Offer,我都经历了什么?
手把手教你配置Jenkins自动化邮件通知
《云原生的本手、妙手和俗手》——2022全国新高考I卷作文
用户交互+格式化输出
coldfusion8后台计划任务拿shell
What have I experienced to become a tester who is harder than development?
12 pictures take you to fully understand service current limit, circuit breaker, downgrade, and avalanche
软件测试要达到一个什么水平才能找到一份9K的工作?
leetcode-1161: Maximum in-layer element sum
勾股数元组 od js
随机推荐
MySQL (6)
12张图带你彻底搞懂服务限流、熔断、降级、雪崩
力扣刷题之爬楼梯(7/30)
如何在 go 程序中暴露 Prometheus 指标
【genius_platform软件平台开发】第七十四讲:window环境下的静态库和动态库的一些使用方法(VC环境)
1782. Count the number of point pairs Double pointer
leetcode-952: Calculate max component size by common factor
数字图像隐写术之卡方分布
Interprocess communication study notes
The PC side determines the type of browser currently in use
加密生活,Web3 项目合伙人的一天
leetcode-399: division evaluation
My first understanding of MySql, and the basic syntax of DDL and DML and DQL in sql statements
简易表白小页面
程序员转正述职报告/总结
初识C语言 -- 数组
GCC Rust获批将被纳入主线代码库,或将于GCC 13中与大家见面
[Map and Set] LeetCode & Niu Ke exercise
Is there a way to earn 300 yuan a day by doing a side business?
充电效果模拟