1. 程式人生 > >9.9遞歸和動態規劃(九)——N皇後

9.9遞歸和動態規劃(九)——N皇後

其它 ace req case create lac any urn distance

/**
* 功能:打印八皇後在8*8棋盤上的各種擺法。當中每一個皇後都不同行、不同列,也不在對角線上。
* 這裏的“對角線”指的是全部的對角線,不僅僅是平分整個棋盤的那兩條對角線。

*/


	static int GRID_SIZE=8;

	/**
	 * 思路:每一行僅僅能擺放一個皇後,因此不須要將棋盤存儲為完整的8*8矩陣。僅僅需一維數組,當中columns[r]=c表示有個皇後位於r行c列。
	 * @param row
	 * @param columns
	 * @param results
	 */
	public static void placeQueen(int row,Integer[] columns,ArrayList<Integer[]> results){
		if(row==GRID_SIZE){
			/*Creates and returns a copy of this object. The precise meaning of "copy" may depend on the class of the object.
			 *  The general intent is that, for any object x, the expression: 
			    x.clone() != x				will be true.
			 *  and that the expression: 
			 	x.clone().getClass() == x.getClass()	will be true. 
			 *	but these are not absolute requirements. While it is typically the case that: 
			 	x.clone().equals(x)	will be true, this is not an absolute requirement. */
			results.add(columns.clone());			
		}else{
			for(int col=0;col<GRID_SIZE;col++){
				if(checkValid(columns,row,col)){
					columns[row]=col;//擺放皇後
					placeQueen(row+1, columns, results);
				}
			}
		}
	}
	
	/**
	 * 檢查(row,column)能否夠擺放皇後。方法:
	 * 檢查有無其它皇後位於同一列或對角線。不必檢查是否在同一行上,由於調用placeQueen時,一次僅僅會擺放一個皇後。

由此可知,這一行是空的。 * @param columns * @param row * @param column * @return */ public static boolean checkValid(Integer[] columns,int row,int column){ for(int r=0;r<row;r++){ int c=columns[r]; /* 檢查同一列是否有皇後 */ if(c==column) return false; /* 檢查對角線: * 若兩行的距離等於兩列的距離。則表示兩個皇後在同一對角線上。

*/ int columnDistance=Math.abs(c-column); int rowDistance=row-r;//row>r,不用取絕對值 if(columnDistance==rowDistance) return false; } return true; }



9.9遞歸和動態規劃(九)——N皇後