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.."]
]

比N-Queens II稍微麻烦一点,其实本质是一样的,解法参考N-Queens II 那道题,区别就是在if(row == n)的时候将list加入,注意:如果有标志可以标记的时候,最好在递归最内层加入list,否则容易出错。

注意输出:此题的输出是一个list里包含若干种解法,每种解法是一个String[],起初把每行当做一个String[]了。

Source

public class Solution {
    public List<String[]> solveNQueens(int n) {
        List<String[]> st = new ArrayList<String[]>();
        if(n == 0) return st;
        int[] col = new int[n];
        
        backtrack(n, 0, st, col);

        return st;
    }
    public void backtrack(int n, int row, List<String[]> st, int[] col){
    	if(row == n){
    		String[] temp = new String[n];
    		for(int i = 0; i < n; i++){
    			StringBuffer a = new StringBuffer();
              	for(int j = 0; j < n; j++){
            		if(col[i] == j){ 
            			a.append("Q");
            		}
            		else a.append(".");
            	}
              	temp[i] = a.toString();
            }
    		
    		st.add(temp);
    		return;
    	}
    
    	for(int i = 0; i < n; i++){
    		col[row] = i;
    		
    		if(isValid(row, col)){
    			backtrack(n, row + 1, st, col);
    		}
    		
    	}
    }
    public boolean isValid(int row, int[] col){
    	for(int i = 0; i < row; i++){
    		if(col[i] == col[row] || Math.abs(col[row] - col[i]) == row - i)
    			return false;
    	}
    	return true;
    }
}


Test

   public static void main(String[] args){
    
    	int n = 4;
    
    	List<String[]> st = new Solution().solveNQueens(n);
    	
    	for(int i = 0; i < st.size(); i++){
    		String[] temp = st.get(i);
    		for(int j = 0; j < temp.length; j++){
    			System.out.print(temp[j]);
    		}
    		System.out.println();
    	}
    	
    }





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用ABT算法求解四皇后问题的Python代码: ``` def is_valid(board, row, col): for i in range(row): if board[i] == col or \ board[i] - i == col - row or \ board[i] + i == col + row: return False return True def backtrack(board, row, n): if row == n: return True for col in range(n): if is_valid(board, row, col): board[row] = col if backtrack(board, row + 1, n): return True return False def asynchronous_backtracking(position, domains, n): if len(position) == n: return position var = max(domains, key=lambda x: len(domains[x])) for val in domains[var]: pos_copy = position.copy() domains_copy = {k: v.copy() for k, v in domains.items()} pos_copy[var] = val domains_copy[var] = {val} if all(len(domains_copy[k]) > 0 for k in domains_copy): if backtrack(pos_copy, 0, n): result = asynchronous_backtracking(pos_copy, domains_copy, n) if result is not None: return result return None n = 4 position = {i: None for i in range(n)} domains = {i: set(range(n)) for i in range(n)} result = asynchronous_backtracking(position, domains, n) print(result) ``` 该代码首先定义了一个`is_valid`函数,用于检查当前位置是否合法。然后定义了一个普通的回溯算法函数`backtrack`,用于求解N皇后问题。最后定义了一个使用ABT算法的函数`asynchronous_backtracking`,该函数从所有未赋值的变量中选择一个具有最小剩余值的变量,然后对该变量的每个可能值进行尝试,直到找到一个可行解或无法继续搜索为止。 在主程序中,将变量和其域初始化为字典,然后调用`asynchronous_backtracking`函数求解四皇后问题。最后输出结果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值