题解 | #N皇后问题#

N皇后问题

https://www.nowcoder.com/practice/c76408782512486d91eea181107293b6

import java.util.*;


public class Solution {
    /**
     *
     * @param n int整型 the n
     * @return int整型
     */
    public int Nqueen (int n) {
        byte[][] map = new byte[n][n];
        return getCount(map, 0, n);
    }

    private int getCount(byte[][] map, int row, int n) {
        int count = 0;
        for (Integer i = 0; i < n; i++) {
            count += seatCount(map, row, i, n);
            clearRow(map, row);
        }
        return count;
    }
    private int seatCount(byte[][] map, int row, int seat, int n) {
        if (!pass(map, row, seat, n)) {
            return 0;
        }
        map[row][seat] = 1;
        if (n - 1 == row) {
            return 1;
        }
        return getCount(map, row + 1, n);
    }
    private void clearRow(byte[][] map, int row) {
        Arrays.fill(map[row], (byte) 0);
    }
    private boolean pass(byte[][] map, int row, int seat, int n) {
        if (row == 0) {
            return true;
        }
        for (int i = 0, px = row; i < row; i++, px--) {
            // 同列排除
            if (map[i][seat] == 1) {
                return false;
            }
            int lx = seat - px;
            int rx = seat + px;
            // 左斜角排除
            if (lx >= 0 && map[i][lx] == 1) {
                return false;
            }
            // 右斜角排除
            if (rx < n && map[i][rx] == 1) {
                return false;
            }
        }
        return true;
    }
}

全部评论

相关推荐

08-22 18:38
已编辑
门头沟学院 Java
蒟蒻一枚呢:团子正式批还没开始面试呢,这咋都考试oc了
美团求职进展汇总
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务