在java中使用递归构建一个简单的棋盘

edqdpe6u  于 2021-06-26  发布在  Java
关注(0)|答案(1)|浏览(430)

我试图通过递归在java中构建一个简单的棋盘布局,但我的问题是,在每个递归调用中,字段的数量减少了一个错误的字段。黑场用“#”表示,白场用空格表示。我用迭代的方法做过,这没问题,但是递归方法让我头疼。

  1. import java.util.Scanner;
  2. public class Chess {
  3. public static int chess(int boardlength) {
  4. if (boardlength == 0) {
  5. return boardlength;
  6. } else {
  7. pattern(boardlength);
  8. System.out.println("\n");
  9. }
  10. return chess(boardlength - 1);
  11. }
  12. public static int pattern(int runs) {
  13. if (runs == 0) {
  14. return runs;
  15. } else {
  16. if (runs % 2 != 0) {
  17. System.out.print("#");
  18. } else {
  19. System.out.print(" ");
  20. }
  21. }
  22. return pattern(runs - 1);
  23. }
  24. public static void main(String[] args) {
  25. Scanner input = new Scanner(System.in);
  26. System.out.print("Length of the board: ");
  27. int boardlength = input.nextInt();
  28. chess(boardlength);
  29. }

}

rhfm7lfc

rhfm7lfc1#

我知道这不是世界上最漂亮的代码,但它确实起到了作用
我使用第二个变量 calls 计算所需的递归次数。有了这个,我可以用 boardlength 用于打印每行的变量。

  1. import java.util.Scanner;
  2. public class Chess {
  3. public static int chess(int boardlength, int calls) {
  4. if (calls == boardlength ) {
  5. return boardlength;
  6. } else {
  7. pattern(boardlength, calls % 2 != 0);
  8. System.out.println("\n");
  9. }
  10. return chess(boardlength, calls + 1);
  11. }
  12. public static int pattern(int runs, boolean pat) {
  13. if (runs == 0) {
  14. return runs;
  15. } else {
  16. if (pat) {
  17. System.out.print("#");
  18. } else {
  19. System.out.print("@");
  20. }
  21. }
  22. return pattern(runs - 1, !pat);
  23. }
  24. public static void main(String[] args) {
  25. Scanner input = new Scanner(System.in);
  26. System.out.print("Length of the board: ");
  27. int boardlength = input.nextInt();
  28. chess(boardlength, 0);
  29. }
  30. }

输出 boardlenth=8 (我将空格改为@)
@#@#@#@#

@#@#@#@

@#@#@#@#

@#@#@#@

@#@#@#@#

@#@#@#@

@#@#@#@#

@#@#@#@

展开查看全部

相关问题