N皇后问题

N皇后问题,可以用回溯算法解决

但是考虑到45度不能有元素存在 135度不能有元素存在还有一列不能有相同元素存在

终止条件,row==n的时候,需要使用将char【】【】 转化为list添加到List<List<String>> ret 中。

package com.lhb.offer;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

/**
 * @author lhb
 * @date 2022/3/14
 */
public class Offer_Nqueue {
    static char[][] nqueue;
    static int n;
    static List<List<String>> ret = new ArrayList<>();
    static void dfs(int row, char[][] nqueue) {
        // 结束条件
        if (row == n) {
            ret.add(ArrayCharToList(nqueue));
            return ;
        }
        for (int col = 0; col < n; col++) {
            if (valid(nqueue, row, col)) {
                nqueue[row][col] = 'Q';
                dfs(row + 1, nqueue);
                nqueue[row][col] = '.';
            }
        }
    }

    private static List<String> ArrayCharToList(char[][] nqueue) {
        List<String> list = new ArrayList<>();
        for (char[] c : nqueue) {
            list.add(String.copyValueOf(c));
        }
        return list;
    }

    private static boolean valid(char[][] nqueue, int row, int col) {
        // 不同列保证
        for (int i = row; i >=0; i--) {
            if (nqueue[i][col] == 'Q') {
                return false;
            }
        }
        // 45度保证
        for (int i = row - 1,j = col + 1; i >=0 && j < n; i--, j++) {
            if (nqueue[i][j] == 'Q') {
                return false;
            }
        }
        // 135度保证
        for (int i = row - 1,j = col - 1; i >=0 && j >= 0; i--, j--) {
            if (nqueue[i][j] == 'Q') {
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String[] s1 = in.nextLine().split(" ");
        n = Integer.parseInt(s1[0]);
        nqueue = new char[n][n];
        for (char [] c : nqueue) {
            Arrays.fill(c, '.');
        }
        dfs( 0, nqueue);
        for (List<String> strings : ret) {
            for (String string : strings) {
                System.out.println(string);
            }
            System.out.println();
        }
    }
}

 

posted @ 2022-03-14 16:58  牵魂  阅读(36)  评论(0)    收藏  举报