首页 > 学院 > 开发设计 > 正文

关于递归的一个例子

2019-11-08 00:58:47
字体:
来源:转载
供稿:网友

我的第一篇博客

package com.selfish.gene.recursive;public class TowersOfHanoi {	PRivate static int countIf = 0;	private static int countElse = 0;	private static int count = 0;	public static void main(String[] args) {		int n = 3;		hanoi(n, 'A', 'B', 'C');		System.out.println("countIf:" + countIf);		System.out.println("countElse:" + countElse);	}	public static void hanoi(int n, char A, char B, char C) {		if (n < 0) {			return;		}		if (n == 1) {			System.out.println(String.format("第 %d次执行if:   Movesheet %d from %c to %c ", ++count, n, A, C));			countIf++;		} else {			hanoi(n - 1, A, C, B);			System.out.println(String.format("第 %d次执行else: Movesheet %d from %c to %c", ++count, n, A, C));			hanoi(n - 1, B, A, C);			countElse++;		}	}}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表