【问题标题】:Storing a specific number pattern in an array将特定数字模式存储在数组中
【发布时间】:2019-10-17 21:07:48
【问题描述】:

我正在处理一个问题并想生成一个特定的模式 这是

1000
1100
1110
1111
0100
0110
0111
0010
0011
0001

使用递归和 for 循环,但是当我编写代码时,它在线程“main”java.lang.StackOverflowError 中给了我一个异常


public class NQueenProblem {
    final static int N = 8;

    void printSolution(int board[][])
    {
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++)
                System.out.print(" "+board[i][j]+" ");
            System.out.println();
        }
    }
    void solveNQUtil(int board[][], int col)
    {
        for (int i = 0; i < N; i++) {
            solveNQUtil(board, col + 1);
        }
    }
    public static void main(String[] args) {

        NQueenProblem Queen = new NQueenProblem();
        int board[][] = new int[N][N];
        Queen.solveNQUtil(board, 0);
    }
}

【问题讨论】:

  • solveNQUtil 无限调用自己。
  • @Ruzihm 你会推荐什么?
  • 只是为了生成不需要此代码的模式,您可以看到最右边的位通过反转连续移动到最左边的位置。

标签: java algorithm backtracking array-algorithms


【解决方案1】:

有一个递归函数,可以打印出尽可能多的行,不管有多少个零和多少列,并让它用一个额外的前导零调用自己。此外,跟踪接下来要编辑的行。

如果前导零的数量等于列数,则返回,因为您已完成:

public class NQueenProblem {
    static void printSolution(int board[][])
    {
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[i].length; j++)
                System.out.print(" "+board[i][j]+" ");
            System.out.println();
        }
    }    
    static void solveNQUtil(int leadingZeros, int startingRow, int board[][])
    {
        int columns = board[0].length;

        if (leadingZeros == columns) return;

        for (int ones = 1; leadingZeros+ones <= columns ; ones++) 
        {
            int curRow = startingRow + ones - 1;

            for (int i=0 ; i<ones ; i++) board[curRow][i+leadingZeros] = 1;
        }

        solveNQUtil(leadingZeros + 1, startingRow + columns - leadingZeros, board);
    }

    public static void main(String[] args) 
    {
        int totalColumns = 4;
        int rows = (int)((totalColumns+1)*totalColumns*0.5); //

        int board[][] = new int[rows][totalColumns];

        solveNQUtil(0, 0, board);
        printSolution(board);
    }
}

【讨论】:

  • 我其实想把它存储在一个数组中并进一步使用它
  • @Swaraj 将其包含在问题的编辑中是件好事
  • @Swaraj 我不知道你是否注意到,但我更新了这个答案以填写一个数组。
【解决方案2】:

您可以通过如下修改 solveNQUtil 方法来克服该错误。 不保证您一定会得到想要的答案。

void solveNQUtil(int board[][], int col)
   {
      if (col == N)
         return;

      for (int i = 0; i < N; i++)
      {
         solveNQUtil(board, col + 1);
      }
   }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-11
    • 1970-01-01
    • 1970-01-01
    • 2017-11-18
    • 1970-01-01
    相关资源
    最近更新 更多