yy629 发表于 2013-1-27 05:06:41

按顺序输出从1到9个环的“回”字图形 [采用递归和非递归]

今天看了一篇文章,打印一个“回”字图形
介绍了用c#完成的,我想我是学java的,就用Java实现吧
代码如下:

public class EchoBox {int len = 0;public void printBox(int len) { // 非递归算法    for (int j = 1; j < 2 * len; j++) {      for (int k = 1; k < 2 * len; k++) {      System.out.print(Math.max(Math.abs(len - j), Math.abs(len - k)) + 1);      }      System.out.println();    }}public void printBox2(int len) { // 递归算法    this.len = len;    this.printBoxUtil(len);}public void printBoxUtil(int r) { // 递归算法 递归打印    this.printOneRow(r);    if (r > 1) {      this.printBoxUtil(r - 1); // 继续递归打印      this.printOneRow(r);    }}private void printOneRow(int r) { // 递归算法 打印其中一行    for (int i = 1; i < len * 2; i++)      System.out.print(Math.max(Math.abs(len - i), r - 1) + 1);    System.out.println();}public static void main(final String[] args) {    EchoBox t = new EchoBox();    for (int i = 1; i < 10; i++) {      System.out.println("\n-------------------");      t.printBox(i); // 非递归      // t.printBox2(i); // 递归    }}}


输出的“回”字图形如下


-------------------
1

-------------------
222
212
222

-------------------
33333
32223
32123
32223
33333

-------------------
4444444
4333334
4322234
4321234
4322234
4333334
4444444

-------------------
555555555
544444445
543333345
543222345
543212345
543222345
543333345
544444445
555555555

-------------------
66666666666
65555555556
65444444456
65433333456
65432223456
65432123456
65432223456
65433333456
65444444456
65555555556
66666666666

-------------------
7777777777777
7666666666667
7655555555567
7654444444567
7654333334567
7654322234567
7654321234567
7654322234567
7654333334567
7654444444567
7655555555567
7666666666667
7777777777777

-------------------
888888888888888
877777777777778
876666666666678
876555555555678
876544444445678
876543333345678
876543222345678
876543212345678
876543222345678
876543333345678
876544444445678
876555555555678
876666666666678
877777777777778
888888888888888

-------------------
99999999999999999
98888888888888889
98777777777777789
98766666666666789
98765555555556789
98765444444456789
98765433333456789
98765432223456789
98765432123456789
98765432223456789
98765433333456789
98765444444456789
98765555555556789
98766666666666789
98777777777777789
98888888888888889
99999999999999999
页: [1]
查看完整版本: 按顺序输出从1到9个环的“回”字图形 [采用递归和非递归]