Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 3194f89

Browse files
algorithms/src/main/java/ivanmarkovic/algorithms/recursion/TowersOfHanoi.java
1 parent c3a1f7b commit 3194f89

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package ivanmarkovic.algorithms.recursion;
2+
3+
/*
4+
Towers of Hanoi:
5+
In the classic problem of the Towers of Hanoi,
6+
you have 3 towers and N disks of
7+
different sizes which can slide onto any tower.
8+
The puzzle starts with disks sorted in ascending order
9+
of size from top to bottom
10+
(i.e., each disk sits on top of an even larger one).
11+
You have the following constraints:
12+
*/
13+
14+
public class TowersOfHanoi {
15+
16+
public static void main(String[] args) {
17+
// TODO Auto-generated method stub
18+
towers(3, "start", "spare", "end");
19+
}
20+
21+
public static void printMove(String start, String end) {
22+
System.out.println("Moving from " + start + " to " + end);
23+
}
24+
25+
public static void towers(int number, String start, String spare, String end) {
26+
if(number == 1)
27+
printMove(start, end);
28+
else {
29+
towers(number - 1, start, end, spare);
30+
towers(1, start, spare, end);
31+
towers(number - 1, spare, start, end);
32+
}
33+
}
34+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /