【问题标题】:Eight Queens Algorithm for Different Starting Points不同起点的八皇后算法
【发布时间】:2016-05-03 10:02:27
【问题描述】:

无论起点如何,我都试图找到解决八皇后问题的方法。下面是我的 Solver 类,但是当我将皇后排成一排而不是第一个时,由于某种原因它不起作用。

import java.util.*; 
public class Queens {
  private static int x;
  private static int y;
  private static ArrayList<Integer> rows = new ArrayList<Integer>();
  public Queens(int index, int row, int pos) {

    for (int i = 0; i<index; i++)
      rows.add(i);
    rows.remove(row);
    x = pos;
    y = row;
  }

public static boolean solve(int row, int[][] board, int N, int pos) {
    board[y][x] = 1;
    System.out.println("row: " + row);
    for(int i = 0; i < 8; i++) {
      for(int j = 0; j < 8; j++) {
        if(board[i][j]==1) System.out.print("Q ");
        else System.out.print("* ");
      }
      System.out.println();
    }
    System.out.println();    
    if(row>=N-1) return true;
    for(int position = pos; position < N; position++) {
      if(isValid(board, rows.get(row), position, N)) {
        board[rows.get(row)][position] = 1;
        if(!solve(row+1, board, N, 0)) {
          board[rows.get(row)][position] = 0;
        } else
          return true;
      }
    }
    return false;
  }

  public static boolean isValid(int[][] board, int y, int x, int N) {
    int i, j;
    for(i = 0; i < y; i++)
      if(board[i][x]==1)
        return false;
    i = y - 1;
    j = x - 1;
    while((i>=0)&&(j>=0))
      if(board[i--][j--]==1) return false;
    i = y - 1;
    j = x + 1;
    while((i>=0)&&(j<N))
      if(board[i--][j++]==1) return false;
    return true;
  }
}

例如,当我将初始皇后放在 board[2][2] 上时,这是我得到的解决方案:

Q * * * * * * * 
* * Q * * * * * 
* * Q * * * * * 
* * * * * Q * * 
* * * * * * * Q 
* Q * * * * * * 
* * * Q * * * * 
* * * * * * Q * 

代码有什么问题?为什么它忽略了最初的部分?提前致谢。

【问题讨论】:

  • 您的调试尝试在哪里?在战略位置插入打印语句以跟踪控制和数据流。深入研究一个特定的问题。描述它并在此处发布详细的输出。

标签: java algorithm recursion backtracking


【解决方案1】:

isValid 中 for 循环的边界是什么?它们是否会阻止您将女王放置在下面有另一个女王的列中?

一个类似的问题也适用于 while 循环——它们能否检测到对角线上有一个皇后,但 在您现在放置的那个下方

【讨论】:

  • 是的,我意识到下面的问题并解决了,但是忘记更新了。基本上我需要另外两个条件来扫描下面的对角线。无论如何,谢谢。
猜你喜欢
  • 1970-01-01
  • 2012-10-24
  • 1970-01-01
  • 2017-11-24
  • 1970-01-01
  • 1970-01-01
  • 2021-08-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多