【问题标题】:Building a simple Chess board with recursion in java在java中使用递归构建一个简单的棋盘
【发布时间】:2021-04-12 13:30:30
【问题描述】:

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

import java.util.Scanner;

public class Chess {

public static int chess(int boardlength) {

    if (boardlength == 0) {
        return boardlength;
    } else {
        pattern(boardlength);
        System.out.println("\n");
    }
    return chess(boardlength - 1);
}

    public static int pattern(int runs) {

        if (runs == 0) {
            return runs;
        } else {
            if (runs % 2 != 0) {
                System.out.print("#");
            } else {
                System.out.print(" ");
            }
        }
        return pattern(runs - 1);
    }

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);
    System.out.print("Length of the board: ");
    int boardlength = input.nextInt();
    chess(boardlength);
}

}

【问题讨论】:

  • 你必须使用递归吗?在我看来,使用简单的循环结构会更容易。
  • 不幸的是,是的。我已经通过嵌套的 for 循环进行了电路板布局,这非常容易和简单,但是将其转换为递归非常困难,至少对我来说是这样

标签: java loops recursion chess


【解决方案1】:

我知道这不是世界上最漂亮的代码,但它可以解决问题

我使用第二个变量calls 来计算所需的递归次数。有了这个,我可以使用boardlength 变量来打印每一行。

import java.util.Scanner;

public class Chess {

  public static int chess(int boardlength, int calls) {

    if (calls == boardlength ) {
      return boardlength;
    } else {
      pattern(boardlength, calls % 2 != 0);
      System.out.println("\n");
    }
    return chess(boardlength, calls + 1);
  }

  public static int pattern(int runs, boolean pat) {

    if (runs == 0) {
      return runs;
    } else {
      if (pat) {
        System.out.print("#");
      } else {
        System.out.print("@");
      }
    }
    return pattern(runs - 1, !pat);
  }

  public static void main(String[] args) {

    Scanner input = new Scanner(System.in);
    System.out.print("Length of the board: ");
    int boardlength = input.nextInt();
    chess(boardlength, 0);
  }

}

使用boardlenth=8 输出(我将空格更改为@)

@#@#@#@#

#@#@#@#@

@#@#@#@#

#@#@#@#@

@#@#@#@#

#@#@#@#@

@#@#@#@#

#@#@#@#@

【讨论】:

  • 谢谢!这确实有效,我不会想到那个解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-17
  • 2017-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-01
相关资源
最近更新 更多