我正在开发类似于 NQueens 问题的程序,但是使用 Bishops 而不是Queens。预期的输出应该是所有可能的解决方案。
public class Bishops {
static int n;
static int count = 1;
private static boolean isSafe(char matrix[][], int row, int col)
{
for (int i = row, j = col; i >= 0 && j >= 0; i--, j--)
if (matrix[i][j] == 'B')
return false;
for (int i = row, j = col; i >= 0 && j < n; i--, j++)
if (matrix[i][j] == 'B')
return false;
return true;
}
private static void bish(char matrix[][], int row)
{
if (row == n)
{
System.out.println(count++);
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++)
System.out.print(matrix[j][i] + " ");
System.out.println();
}
System.out.println();
System.out.println(count++);
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++)
System.out.print(matrix[i][j] + " ");
System.out.println();
}
System.out.println();
return;
}
for (int i = 0; i < n; i++){
if (isSafe(matrix, row, i)){
matrix[row][i] = 'B';
bish(matrix, row + 1);
matrix[row][i] = '*';
}
}
}
public static void main(String[] args)
{
Scanner sc = new Scanner( System.in );
System.out.print("Enter a value: ");
n = sc.nextInt();
char[][] matrix = new char[n][n];
for (int i = 0; i < n; i++) {
Arrays.fill(matrix[i], '*');
}
bish(matrix, 0);
}
}
当我输入两个时,我的输出返回正确的四个解,但是当我输入三个时,它应该返回二十个时的十个解。任何帮助将不胜感激。