原创

[百战LeetCode][41. N皇后问题]


==========================努力奋斗财源广进==========================

一、算法题目

N 皇后问题是指在 n * n 的棋盘上要摆 n 个皇后, 要求:任何两个皇后不同行,不同列也不在同一条斜线上, 求给一个整数 n ,返回 n 皇后的摆法数。

1、我的题解

import java.util.*;
public class Solution {
    /**
     *
     * @param n int整型 the n
     * @return int整型
     */
    Set<Integer> column = new HashSet<Integer>(); //标记列不可用
    Set<Integer> posSlant = new HashSet<Integer>();//标记正斜线不可用
    Set<Integer> conSlant = new HashSet<Integer>();//标记反斜线不可用
    int result = 0;

    public int Nqueen (int n) {
        // write code here
        compute(0, n);
        return result;
    }
    private void compute(int i, int n) {
        if (i == n) {
            result++;
            return;
        }
        for (int j = 0; j < n; j++) {
            if (column.contains(j) || posSlant.contains(i - j) ||
                    conSlant.contains(i + j)) {
                continue;
            }
            column.add(j);//列号j
            posSlant.add(i - j);//行号i - 列号j 正斜线
            conSlant.add(i + j);//行号i + 列号j 反斜线
            compute(i + 1, n); //计算下一行
            column.remove(j); //完成上一步递归计算后,清除
            posSlant.remove(i - j);
            conSlant.remove(i + j);
        }
    }
}


2、优秀题解

//待定

三、解法心得

四、自我监督

评论区记录复习记录

  • 作者:北斗七点半联系作者
  • 发表时间:2022-12-11 23:08
  • 版权声明:禁止转载
  • 非公众号转发
  • 评论