其他分享
首页 > 其他分享> > 2022.02.22 - 248.八皇后

2022.02.22 - 248.八皇后

作者:互联网

文章目录

1. 题目

在这里插入图片描述

2. 思路

(1) 回溯法

3. 代码

import java.util.*;

public class Test {
    public static void main(String[] args) {
    }
}

class Solution {
    public int n;
    public List<List<String>> res;
    public List<Integer> list;
    public Set<Integer> col;
    public Set<Integer> l1;
    public Set<Integer> l2;


    public List<List<String>> solveNQueens(int n) {
        this.n = n;
        res = new ArrayList<>();
        list = new ArrayList<>();
        col = new HashSet<>();
        l1 = new HashSet<>();
        l2 = new HashSet<>();
        backtrack(0);
        return res;
    }

    public void backtrack(int index) {
        if (index == n) {
            if (list.size() == n) {
                add();
            }
            return;
        }
        for (int i = 0; i < n; i++) {
            int ll1 = index - i;
            int ll2 = index + i;
            if (!col.contains(i) && !l1.contains(ll1) && !l2.contains(ll2)) {
                col.add(i);
                l1.add(ll1);
                l2.add(ll2);
                list.add(i);
                backtrack(index + 1);
                col.remove(i);
                l1.remove(ll1);
                l2.remove(ll2);
                list.remove(list.size() - 1);
            }
        }
    }

    public void add() {
        List<String> temp = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            char[] chars = new char[n];
            Arrays.fill(chars, '.');
            chars[list.get(i)] = 'Q';
            temp.add(String.valueOf(chars));
        }
        res.add(temp);
    }
}

标签:index,248,22,int,list,2022.02,add,new,public
来源: https://blog.csdn.net/qq_44021223/article/details/123070241