34题 N-Queens II

该博客主要介绍了如何解决N皇后问题的变种,即找出所有不同的解决方案数量。通过递归方法和回溯策略,实现了在棋盘上放置N个皇后,使得任意两个皇后不处于同一行、同一列或同一对角线上。代码中定义了关键函数totalNQueens()、helper()、isValid()和Draw(),分别用于计算解决方案总数、递归放置皇后、检查当前位置是否有效以及构建解决方案的可视化表示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

N-Queens II

Description
According to N-Queens problem.

Now, instead outputting board configurations, return the total number of distinct solutions.

public class Solution {
    /**
     * @param n: The number of queens.
     * @return: The total number of distinct solutions.
     */
    public int totalNQueens(int n) {
        // write your code here
        List<List<String>> results = new LinkedList<>();
        if (n <= 0) { 
          return 0; 
         } 
        List<Integer> cols = new ArrayList<>();
        helper(results, n, cols);
        return results.size();
    }
    public void helper(List<List<String>> results , int n, List<Integer> cols) {
    // reach solution
      if (cols.size() == n) {
        results.add(Draw(cols));
        return;
       }
      for (int i = 0; i < n; i++) {
         if(!isValid(cols, i)){
             continue ;
         }
         cols.add(i) ;
         helper(results , n, cols) ;
         cols.remove(cols.size()-1) ;
       
     }
    }
    public boolean isValid(List<Integer> cols , int i) {
      // only check rows above current one
     int row = cols.size() ;
     for(int j =0 ; j < cols.size() ; j++){
         if(i == cols.get(j)){
             return false ;
         }
         if(row + i == j + cols.get(j)){
             return false ;
         }
         if(row - i == j - cols.get(j)){
             return false ;
         }
     }
       return true;
    }
  // build solution from temporary chessboard
    public List<String> Draw(List<Integer> cols) {
       List<String> result = new ArrayList<>();
       for (int i = 0; i < cols.size(); i++) {
          StringBuilder sb = new StringBuilder() ;
          for(int j = 0; j < cols.size(); j++){
              sb.append(j == cols.get(i) ? 'Q' : '.') ;
          }
          result.add(sb.toString()) ;
        }
        return result;
    }
    

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值