(Java)LeetCode-51. N-Queens

The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.

Given an integer n, return all distinct solutions to the n-queens puzzle.

Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively.

For example,
There exist two distinct solutions to the 4-queens puzzle:

[
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]


著名的八皇后問題,早有耳聞,今日終得一見,難得難得。

最典型的回溯算法,逐行來找能放皇后的位置,若到最後沒有皇后可以放,就回溯去掉前面的狀態。

自己寫完後,去看了別人的代碼,都差不多,就是有一個地方和別人不太一樣,就是如何判斷一個位置是否能放一個皇后,別人的做法的是用一個數組存儲前面已經放下的皇后的位置,然後再來判斷,這樣寫起來比較簡單,省地方,我是直接的找到這個點的上下左右幾個方向上看有沒有皇后。這個地方不太成熟,要向別人學習。不過還是貼上我自己寫的代碼,畢竟寫了蠻久的。


代碼如下:




	public List<List<String>> solveNQueens(int n) {
		List<List<String>> result = new ArrayList<List<String>>();
		List<String> line = new ArrayList<String>();
		char[][] cube = new char[n][n];
		for(int i = 0; i < cube.length; i++){
			for(int j = 0; j < cube[i].length; j++){
				cube[i][j] = '.';
			}
		}
		boolean[] flags = new boolean[n];
		solveNQueens(result, cube, flags, n, 0);
        return result;
    }

	private void solveNQueens(List<List<String>> result, char[][] cube,boolean[] flags,int n, int cnt) {
		// TODO Auto-generated method stub
		if(cnt == n){
			List<String> list = new ArrayList<String>();
			for(char[] ch : cube){
				list.add(new String(ch));
			}
			result.add(list);
			return ;
		}
		for(int i = 0; i < flags.length; i++){
			if(flags[i] == false){
				List<Integer> temp = aPosition(cube, i);
				if(temp.size() == 0){
					break;
				}
				for(int t : temp){
					cube[i][t] = 'Q';
					flags[i] = true;
					solveNQueens(result, cube, flags, n , cnt+1);
					cube[i][t] = '.';
					flags[i] = false;
				}
				break;
			}
		}
	}

	private List<Integer> aPosition(char[][] cube, int num) {
		// TODO Auto-generated method stub
		List<Integer> result = new ArrayList<Integer>();
		int n = cube.length;
		boolean flag = false;
		for(int i = 0; i < n; i++){			//the direction is "--"
			if(cube[num][i] == 'Q'){
				return result;
			}
		}
		
		for(int i = 0; i < n; i++){
			for(int j = 0; j < n; j++){		//the direction is "|"
				if(cube[j][i] == 'Q'){
					flag = true;
					break;
				}
			}
			if(flag == false){
				if(num >= i){					// the direction is "\"
					int dif = num - i;
					for(int j = 0; j + dif <= n-1; j++){ 
						if(cube[j+dif][j] == 'Q'){
							flag = true;
							break;
						}
					}
				}else{
					int dif = i - num;
					for(int j = 0; j + dif <= n-1; j++){
						if(cube[j][j+dif] == 'Q'){
							flag = true;
							break;
						}
					}
				}
				if(flag == false){
					if(num + i <= n-1){				//the direction is "/"
						int sum = i + num;
						for(int j = 0; sum >= j; j++ ){
							if(cube[j][sum-j] == 'Q'){
								flag = true;
								break;
							}
						}
					}else{
						int sum = i + num;
						for(int j = n-1; sum-j <= n-1; j--){
							if(cube[sum-j][j] == 'Q'){
								flag = true;
								break;
							}
						}
					}
				}
			}
			if(flag == false){
				result.add(i);
			}else{
				flag = false;
			}
		}
		return result;
	}

	public static void main(String[] args){
    	Solution sol = new Solution();
    	System.out.println("start");
    	List<List<String>> re = sol.solveNQueens(4);
    	for(List<String> l : re){
    		System.out.println(l);
    	}
    }



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章