Recursion 八皇后问题 @CareerCup

递归+回溯,不多说了。唯一要注意的是在每次记录一个可行的方案时,要复制一份数组,在Java中可以通过

1 循环复制

2 clone() 方法

3 System.arraycopy() 方法

这里按照书上,用了clone()方法!


package Recursion;

import java.util.ArrayList;

/**
 * Write an algorithm to print all ways of arranging eight queens on a chess board so that none of them share the same row, column or diagonal.

译文:

经典的八皇后问题,即在一个8*8的棋盘上放8个皇后,使得这8个皇后无法互相攻击( 任意2个皇后不能处于同一行,同一列或是对角线上),输出所有可能的摆放情况。
 
 *
 */
public class S9_9 {

	public static int GRID_SIZE = 8;
	
	public static void main(String[] args) {
		ArrayList<Integer[]> results = new ArrayList<Integer[]>();
		Integer[] columns = new Integer[GRID_SIZE];
		clear(columns);
		placeQueens(0, columns, results);
		printBoards(results);
		System.out.println(results.size());
	}
	
	// column = columns[row]
	public static void placeQueens(int row, Integer[] columns, ArrayList<Integer[]> results) {
		if(row == GRID_SIZE){
			results.add(columns.clone());		// 注意这里要做一个复制!
			return;
		}
		
		for(int col=0; col<GRID_SIZE; col++){
			if(isValid(row, col, columns)){
				columns[row] = col;
				placeQueens(row+1, columns, results);
				columns[row] = -1;
			}
		}
	}
	
	public static boolean isValid(int row, int col, Integer[] columns){
		if(columns[row] != -1){
			return false;
		}
		
		for(int r=0; r<row; r++){
			if(columns[r] == col){
				return false;
			}
			if(Math.abs(r-row) == Math.abs(columns[r]-col)){
				return false;
			}
		}
		
		return true;
	}
	

	public static void clear(Integer[] columns) {
		for (int i = 0; i < GRID_SIZE; i++) {
			columns[i] = -1;
		}
	}
	
	public static void printBoards(ArrayList<Integer[]> boards) {
		for (int i = 0; i < boards.size(); i++) {
			Integer[] board = boards.get(i);
			printBoard(board);
		}
	}
	
	public static void printBoard(Integer[] columns) {
		System.out.println("-----------------");
		for(int i = 0; i < GRID_SIZE; i++){
			System.out.print("|");
			for (int j = 0; j < GRID_SIZE; j++){
			    if (columns[i] == j) {
			    	System.out.print("Q|");
			    } else {
			    	System.out.print(" |");
			    }
			}
			System.out.println("\n-----------------");
		}
		System.out.println("");
	}
	
	

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值