34 - N皇后问题 II

2017.9.18

public class Solution {
    /*
     * @param n: The number of queens.
     * @return: The total number of distinct solutions.
     */
   	public static int res;
    public static int totalNQueens(int n) {
        // write your code here
    	res = 0;
    	if(n == 0 || n==1){
    	    return 1;
    	}
        char [][]arr = new char[n][n];
    	for(int i = 0; i< n; i++){
    		for(int j = 0;j < n;j++){
    			arr[i][j] = '.';
    		}
    	}
    	res = solveNQueens(n,arr,0);
    	return res;
    }
    
      public static boolean judgeAround(char [][]arr,int i,int j){
		//检测同一行
		int n = arr.length;
		for(int k = 0; k < n ; k++){
			if(arr[i][k] =='Q' || arr[k][j] =='Q'){
				return false;
			}
		}
		int x = i;
		int y = j;
		while( x >= 0 && y >= 0){
			if(arr[x][y] == 'Q'){
				return false;
			}
			x--;
			y--;
		}
		x = i;
		y = j;
		while( x >= 0 && y <= n-1){
			if(arr[x][y] =='Q'){
				return false;
			}
			x--;
			y++;
		}
		x = i;
		y = j;
		while( x <= n-1 && y >= 0 ){
			if(arr[x][y] == 'Q'){
				return false;
			}
			x++;
			y--;
		}
		x = i;
		y = j;
		while( x <= n-1 && y <= n-1 ){
			if(arr[x][y] == 'Q'){
				return false;
			}
			x++;
			y++;
		}
		return true;
		
	}
	
    public static int solveNQueens(int n,char [][]arr,int k) {
        // write your code here
    	if(k >= n){
    		return res;
    	}
    	for(int i = 0; i < n; i++){
    		if(judgeAround(arr,k,i) == true){
    			char [][]arr_tmp = new char[n][n];
    			for(int h = 0; h< n; h++){
    	    		for(int j = 0;j < n;j++){
    	    			arr_tmp[h][j] = arr[h][j];
    	    		}
    	    	}
    			arr_tmp[k][i] = 'Q';
    			if(k == n-1){
    				res = res+1;
    			}
    			else{
    				solveNQueens(n,arr_tmp,k+1);
    			}
    		}
    	}
    	return res;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
N 皇后问题是一个经典的算法问题,它的目标是在 $N \times N$ 的棋盘上放置 $N$ 个皇后,使得它们互相之间不能攻击到对方。皇后可以攻击同一行、同一列或同一对角线上的其他皇后。 解决这个问题的常用方法是回溯算法。回溯算法是一种深度优先搜索的算法,它通常用于解决组合问题。在回溯算法中,我们尝试每一种可能的情况,如果当前情况不满足条件,就回溯到上一个状态并尝试下一种情况,直到找到满足条件的解或者所有情况都尝试完毕。 下面是 N 皇后问题的回溯算法实现: ```python def solveNQueens(n: int) -> List[List[str]]: def backtrack(board, row): if row == n: res.append(["".join(row) for row in board]) return for col in range(n): if not cols[col] and not diag1[row + col] and not diag2[row - col]: board[row][col] = "Q" cols[col], diag1[row + col], diag2[row - col] = True, True, True backtrack(board, row + 1) board[row][col] = "." cols[col], diag1[row + col], diag2[row - col] = False, False, False res = [] board = [["."] * n for _ in range(n)] cols, diag1, diag2 = [False] * n, [False] * (2 * n - 1), [False] * (2 * n - 1) backtrack(board, 0) return res ``` 在回溯算法中,我们首先初始化一个 $N \times N$ 的棋盘,然后从第一行开始尝试每一列上放置皇后的情况。如果当前位置可以放置皇后,就递归到下一行继续尝试放置皇后,否则回溯到上一行并尝试下一列。当所有皇后都放置完毕时,我们将当前棋盘的状态加入结果集中。 在实现中,我们使用了三个数组来记录哪些列、哪些对角线已经有皇后了,以便在放置皇后时进行判断。其中,cols 数组记录哪些列已经有皇后,diag1 数组记录从左上角到右下角的对角线上哪些位置已经有皇后,diag2 数组记录从右上角到左下角的对角线上哪些位置已经有皇后。 以上就是 N 皇后问题的解决方法,希望能够帮助你深入浅出地理解算法的实现过程。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值