N皇后问题-JAVA版

算法描述:

TODO

代码实现:

package com.dicuu.algorithm;

import java.util.Arrays;
import java.util.Scanner;

public class NQueen {
    private static int queenNum;
    private static int[] hash;
    private static int count = 0;

    public static void placeQueen(int m) {
        if (m > queenNum) {
            count++;
            for (int i = 1; i <= queenNum; i++) {
                System.out.print(hash[i]);
            }
            System.out.println();
            System.out.println(Arrays.toString(hash));
            for (int i = 1; i <= queenNum; i++) {
                int column = hash[i];
                for (int j = 1; j <= queenNum; j++) {
                    if (j != column) {
                        System.out.print("* ");
                    } else {
                        System.out.print("Q ");
                    }
                }
                System.out.println();
            }
            return;
        }
        for (int i = 1; i <= queenNum; i++) {
            if (!isConfilct(m, i)) {
                hash[m] = i;
                placeQueen(m + 1);
                hash[m] = -1;
            }
        }
    }

    private static boolean isConfilct(int row, int column) {
        if (row == 1) {
            return false;
        }
        for (int i = 1; i < row; i++) {
            if (hash[i] == column || (column - row) == (hash[i] - i) || (row - column) == (i - hash[i])
                    || (row + column) == (hash[i] + i)) {
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        queenNum = sc.nextInt();
        hash = new int[queenNum + 1];
        Arrays.fill(hash, -1);
        placeQueen(1);
        System.out.println(count);
    }
}
Tags:JavaAlgorithm

著作权归作者所有。
商业转载请联系作者获得授权,非商业转载请注明出处。
原文作者:liwiki
原文标题:N皇后问题-JAVA版
原文链接:https://blog.dicuu.com/java/343.html

上一篇
打赏
没有啦~

该页面评论已关闭