八皇后问题(Java)

八皇后问题(Java)

八皇后问题,是一个古老而著名的问题,是回溯算法的典型案例。该问题是国际西洋棋棋手马克斯·贝瑟尔于1848年提出:在8×8格的国际象棋上摆放八个皇后,使其不能互相攻击,即任意两个皇后都不能处于同一行、同一列或同一斜线上,问有多少种摆法

八皇后问题算法思路
  1. 先把第一个皇后放在第一行第一列
  2. 第二个皇后放在第二行第一列然后判断是否符合条件,如果不符合条件,就继续放在第二行第二列,第二行第三列…一次把所有列放完
  3. 以后的皇后,同第二个皇后的方法类似,直到第八个皇后都放在棋盘上且满足条件
  4. 当得到一个正确解后,栈回退到上一个栈,回溯将第一个皇后,放在第一列的所有解循环得到
  5. 再回溯让第一个皇后放在第二列,依次循环得到所有解
代码如下
public class Empress {
	int max=8;
	int []array=new int [max];
	static int count=0;
	public static void main(String[] args) {
		Empress empress =new Empress();
		empress.check(0);
		System.out.printf("一共有%d个解法!",count);
	}
	public void check(int  n) {//放置皇后
		if(n==max) {//说明8个皇后放置完成
			print();
			return;
		}
		for(int i=0;i<max;i++) {
			array[n]=i;//先放置在该行第一列
			if(judge(n)) {//若不冲突
				check(n+1);//递归放置下一个皇后
			}
			//如果冲突,就继续执行array[n]=i;即将皇后依次后移
		}
	}
	private boolean judge(int n) {
		for(int i=0;i<n;i++) {
			//若array[i]==array[n],则第n个皇后与第n-1个皇后在同一列
			//若Math.abs(n-i)==Math.abs(array[n]-array[i]),
			if(array[i] == array[n] || Math.abs(n-i) == Math.abs(array[n] - array[i]) ) {
				return false;
			}
		}
		return true;
	}
	private void print() {//打印
		for(int i=0;i<array.length;i++) {
			System.out.print(array[i]+" ");
		}
		System.out.println();
		count++;
	}
	
}

运行结果
0 4 7 5 2 6 1 3 
0 5 7 2 6 3 1 4 
0 6 3 5 7 1 4 2 
0 6 4 7 1 3 5 2 
1 3 5 7 2 0 6 4 
1 4 6 0 2 7 5 3 
1 4 6 3 0 7 5 2 
1 5 0 6 3 7 2 4 
1 5 7 2 0 3 6 4 
1 6 2 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1 3 6 
5 2 4 6 0 3 1 7 
5 2 4 7 0 3 1 6 
5 2 6 1 3 7 0 4 
5 2 6 1 7 4 0 3 
5 2 6 3 0 7 1 4 
5 3 0 4 7 1 6 2 
5 3 1 7 4 6 0 2 
5 3 6 0 2 4 1 7 
5 3 6 0 7 1 4 2 
5 7 1 3 0 6 4 2 
6 0 2 7 5 3 1 4 
6 1 3 0 7 4 2 5 
6 1 5 2 0 3 7 4 
6 2 0 5 7 4 1 3 
6 2 7 1 4 0 5 3 
6 3 1 4 7 0 2 5 
6 3 1 7 5 0 2 4 
6 4 2 0 5 7 1 3 
7 1 3 0 6 4 2 5 
7 1 4 2 0 6 3 5 
7 2 0 5 1 4 6 3 
7 3 0 2 5 1 6 4 
一共有92个解法!
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 这取决于您想要的代码复杂程度。但是,一般来说,在Java中解决八皇后问题的代码可以如下所示: public class EightQueens { static int GRID_SIZE = 8; /* * Returns a 2D array with all positions * set to 0 */ static int[][] initializeGrid() { int grid[][] = new int[GRID_SIZE][GRID_SIZE]; for (int row = 0; row < GRID_SIZE; row++) { for (int col = 0; col < GRID_SIZE; col++) { grid[row][col] = 0; } } return grid; } /* * Prints the given 2D array */ static void printGrid(int grid[][]) { for (int row = 0; row < GRID_SIZE; row++) { for (int col = 0; col < GRID_SIZE; col++) { System.out.print(grid[row][col] + " "); } System.out.println(); } } /* * Checks if it is safe to place a queen at * position (row,col). */ static boolean isSafe(int grid[][], int row, int col) { int i, j; /* * Check this row on left side */ for (i = 0; i < col; i++) if (grid[row][i] == 1) return false; /* * Check upper diagonal on left side */ for (i = row, j = col; i >= 0 && j >= 0; i--, j--) if (grid[i][j] == 1) return false; /* * Check lower diagonal on left side */ for (i = row, j = col; j >= 0 && i < GRID_SIZE; i++, j--) if (grid[i][j] == 1) return false; return true; } /* * Solves the N Queen problem using * Backtracking. */ static boolean solveNQUtil(int grid[][], int col) { /* * base case: If all queens are placed * then return true */ if (col >= GRID_SIZE) return true; /* * Consider this column and try placing * this queen in all rows one by one */ for (int i = 0; i < GRID_SIZE; i++) { /* * Check if queen can be placed on * board[i][col] */ if (isSafe(grid, i, col)) { /* * Place this queen in board[i][col] */ grid[i][col] = 1; /* recur to place rest of the queens */ if (solveNQUtil(grid, col + 1)) return true; /* * If placing queen in board[i][col] * doesn't lead to a solution, then * remove queen from board[i][col] */ grid[i][col] = 0; // BACKTRACK } } /* * If queen can not be place in any row in * this column col then return false */ return false; } /* * This function solves the N Queen problem using * Backtracking. It mainly uses solveNQUtil() to * solve the problem. It returns false if queens * cannot be placed, otherwise return true and * prints placement of queens in the form of 1s. * Please note that there may be more than one * solutions, this function prints one of the * feasible solutions. */ static void solveNQ() { int grid[][] = initializeGrid(); if (solveNQUtil(grid, 0) == false) { System.out.println("Solution does not exist"); return; } printGrid(grid); } public static void main(String args[]) { solveNQ(); } } ### 回答2: 八皇后问题是一个经典的算法问题,其目标是在8×8的棋盘上放置8个皇后,使得任意两个皇后不在同一行、同一列或同一对角线上。 下面是一个解决八皇后问题Java代码: ```java public class EightQueens { private static final int SIZE = 8; // 棋盘大小 private static final int EMPTY = 0; // 空位置 private static final int QUEEN = 1; // 皇后位置 private int[][] board; // 棋盘 public EightQueens() { board = new int[SIZE][SIZE]; } // 打印棋盘 public void printBoard() { for (int i = 0; i < SIZE; i++) { for (int j = 0; j < SIZE; j++) { if (board[i][j] == QUEEN) { System.out.print("Q "); } else { System.out.print(". "); } } System.out.println(); } System.out.println(); } // 检查位置是否安全 private boolean isSafe(int row, int col) { // 检查同一列 for (int i = 0; i < row; i++) { if (board[i][col] == QUEEN) { return false; } } // 检查左上对角线 for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) { if (board[i][j] == QUEEN) { return false; } } // 检查右上对角线 for (int i = row, j = col; i >= 0 && j < SIZE; i--, j++) { if (board[i][j] == QUEEN) { return false; } } return true; } // 回溯算法求解 private boolean solve(int row) { if (row >= SIZE) { return true; } for (int col = 0; col < SIZE; col++) { if (isSafe(row, col)) { board[row][col] = QUEEN; if (solve(row + 1)) { return true; } board[row][col] = EMPTY; // 回溯 } } return false; } public static void main(String[] args) { EightQueens eightQueens = new EightQueens(); if (eightQueens.solve(0)) { eightQueens.printBoard(); } else { System.out.println("No solution found!"); } } } ``` 以上代码使用了回溯算法解决八皇后问题。首先创建一个8×8的棋盘(二维数组)作为问题的解空间。然后定义了`isSafe`方法来检查位置是否安全,即是否满足不在同一行、同一列和同一对角线的条件。接着使用递归函数`solve`来尝试放置一个皇后,如果该位置安全,则继续递归放置下一个皇后,如果无法找到合适的位置,则进行回溯。最后在`main`函数中调用`solve`方法来求解问题,并打印出解。如果找到解,则输出棋盘的位置,否则输出"No solution found!"。 这段代码可以解决八皇后问题,并输出一个合法的棋盘位置。 ### 回答3: 八皇后问题是一个经典的问题,要求在8x8的国际象棋棋盘上摆放8个皇后,使得每个皇后都不能互相攻击,即任意两个皇后不能处于同一行、同一列或同一对角线上。 以下是一个用Java语言实现的解决八皇后问题的代码: ```java public class EightQueens { private static final int BOARD_SIZE = 8; private static int[] queens; // 存储皇后所在列的位置 public static void main(String[] args) { queens = new int[BOARD_SIZE]; solve(0); // 从第0行开始逐行放置皇后 } private static void solve(int row) { if (row == BOARD_SIZE) { printSolution(); } else { for (int col = 0; col < BOARD_SIZE; col++) { if (isValid(row, col)) { queens[row] = col; solve(row + 1); } } } } private static boolean isValid(int row, int col) { for (int i = 0; i < row; i++) { if (queens[i] == col || queens[i] - queens[row] == row - i || queens[i] - queens[row] == i - row) { return false; } } return true; } private static void printSolution() { System.out.println("一个有效的解决方案:"); for (int row = 0; row < BOARD_SIZE; row++) { for (int col = 0; col < BOARD_SIZE; col++) { if (queens[row] == col) System.out.print("Q "); else System.out.print(". "); } System.out.println(); } System.out.println(); } } ``` 这段代码使用回溯法来解决八皇后问题。通过递归遍历每一行的每一个列,如果在当前位置放置皇后不会导致攻击,则将该位置视为一个解决方案的一部分,并进入下一行。如果所有行都放置了皇后,即找到一个有效解决方案,则将其打印出来。 最后,通过调用 `solve(0)` 来开始求解八皇后问题。程序会输出所有找到的解决方案。 请注意,这段代码只能找到一个解决方案,如果需要找到所有的解决方案,则需要进行一些修改。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值