八皇后问题独立解JAVA代码

import java.util.HashMap;
import java.util.Map;

/**
 * 八皇后问题
 * 
 * @author Watson Xu
 * @since 2016年4月8日 v1.0.0
 */
public class Queens {
	private Integer queens;

	// 同栏是否有皇后,1表示有
	private Integer[] column;

	// 右上至左下是否有皇后
	private Integer[] rup;

	// 左上至右下是否有皇后
	private Integer[] lup;

	// 解答
	private Integer[] queen;
	
	// 独立解 及其对称图形
	private Map<String, String> results = new HashMap<String, String>();

	// 解答编号
	private int num;

	public Queens(int queens) {
		this.queens = queens;
		column = new Integer[queens + 1];
		rup = new Integer[(2 * queens) + 1];
		lup = new Integer[(2 * queens) + 1];
		queen = new Integer[queens + 1];
		
		for (int i = 0; i <= queens; i++) {
			column[i] = queen[i] = 0;
		}

		for (int i = 0; i <= (2 * queens); i++) {
			rup[i] = lup[i] = 0; // 初始定义全部无皇后
		}

		
	}

	public void backtrack(int i) {
		if (i > queens) {
			showAnswer();
		} else {
			for (int j = 1; j <= queens; j++) {
				if ((column[j] == 0) && (rup[i + j] == 0) && (lup[i - j + queens] == 0)) {
					// 若无皇后
					queen[i] = j;
					// 设定为占用
					column[j] = rup[i + j] = lup[i - j + queens] = 1;
					backtrack(i + 1); // 循环调用
					column[j] = rup[i + j] = lup[i - j + queens] = 0;
				}
			}
		}
	}

	protected void showAnswer() {
		num++;
		if(!isIndependence(num)) return;
		System.out.println("解答" + num + ":");
		for (int y = 1; y <= queens; y++) {
			for (int x = 1; x <= queens; x++) {
				if (queen[y] == x) {
					System.out.print(" Q");
				} else {
					System.out.print(" .");
				}
			}
			System.out.println(" ");
		}
		System.out.println();
	}
	
	protected boolean isIndependence(int number) {
		// 自身
		String newSolution = resultToString(queen);
		String flag = results.get(newSolution);

		if (flag != null) {
			//System.out.println("非独立解答解答, 同解答 " + flag + " 对称。");
			return false;
		}

		// 左右对称
		Integer[] leftRight = new Integer[queen.length];
		// 上下对称
		Integer[] upDown = new Integer[queen.length];
		// 左上右下对称
		Integer[] lurd = new Integer[queen.length];
		// 右上左下对称
		Integer[] ruld = new Integer[queen.length];
		// 顺时针第1次旋转
		Integer[] cw1 = new Integer[queen.length];
		for (int i = 1; i < queen.length; i++) {
			leftRight[i] = queen[queen.length - i];
			upDown[i] = queen.length - queen[i];
			lurd[queen.length - queen[i]] = queen.length - i;
			ruld[queen[i]] = i;
			cw1[queen[i]] = queen.length - i;
		}
		// 顺时针第2次旋转
		Integer[] cw2 = new Integer[queen.length];
		for (int i = 1; i < queen.length; i++) {
			cw2[cw1[i]] = queen.length - i;
		}
		// 顺时针第3次旋转
		Integer[] cw3 = new Integer[queen.length];
		for (int i = 1; i < queen.length; i++) {
			cw3[cw2[i]] = queen.length - i;
		}

		results.put(newSolution, number + "_self");
		putNewSolution(leftRight, number + "_lr");
		putNewSolution(upDown, number + "_ud");
		putNewSolution(lurd, number + "_lurd");
		putNewSolution(ruld, number + "_ruld");
		putNewSolution(cw1, number + "_cw1");
		putNewSolution(cw2, number + "_cw2");
		putNewSolution(cw3, number + "_cw3");

		return true;
	}
	
	protected void putNewSolution(Integer[] temp, String mark) {
		String newSolution = resultToString(temp);
		String flag = results.get(newSolution);
		
		if(flag == null) {
			results.put(newSolution, mark);
		}
	}
	
	protected String resultToString(Integer[] result) {
		StringBuilder sb = new StringBuilder();
		for (int i = 1; i < queen.length; i++) {
			sb.append(result[i]);
		}
		return sb.toString();
	}
	
	// 计算复杂度 15720
	public static void main(String[] args) {
		Queens queen = new Queens(8);
		queen.backtrack(1);
	}
	
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值