题解 | N皇后问题

N皇后问题

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

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param n int整型 the n
     * @return int整型
     */
    static  public int Nqueen (int n) {
        int[][] t = new int[n][n];
        List<int[]> result = new ArrayList<int[]>();
        List<int[]> list = new LinkedList<int[]>();
        dfs(t, result, list, 0, 0);
        return result.size();
    }
    static public void dfs(int[][] t, List<int[]> result, List<int[]> list, int x,
                           int y) {
        if (list.size() == t.length) {
            result.add(new int[] {x, y});
            return;
        }
        if (x > list.size()) {
            return;
        }
        for (int i = x; i < t.length; i++) {
            for (int j = y; j < t.length; j++) {
                if (checkLine(t, i) && checkRow(t, j) && checkObliqueHypotenuse(t, i, j) &&
                        checkBackslash(t, i, j)) {
                    t[i][j] = 1;
                    list.add(new int[] {i, j});
                    dfs(t, result, list, i, j);
                    t[i][j] = 0;
                    list.remove(list.size() - 1);
                }
            }
            y = 0;
        }
    }


    //校验同一行是否有1
    static public boolean checkLine(int[][] t, int x) {
        for (int i = 0; i < t.length; i++) {
            if (t[x][i] == 1) {
                return false;
            }
        }
        return true;
    }

    //校验同一列是否有1
    static public boolean checkRow(int[][] t, int y) {
        for (int i = 0; i < t.length; i++) {
            if (t[i][y] == 1) {
                return false;
            }
        }
        return true;
    }

    //校验正斜边

    static public boolean checkObliqueHypotenuse(int[][] t, int x, int y) {

        int i = x, j = y;

        //往上走,
        while (i >= 0 && j < t.length) {
            if (t[i][j] == 1) {
                return false;
            }
            i--;
            j++;
        }

        i = x;
        j = y;
        while (j >= 0 && i < t.length) {
            if (t[i][j] == 1) {
                return false;
            }
            i++;
            j--;
        }
        return true;
    }

    static public boolean checkBackslash(int[][] t, int x, int y) {
        int i = x, j = y;
        //往上走,
        while (i < t.length && j < t.length) {
            if (t[i][j] == 1) {
                return false;
            }
            i++;
            j++;
        }
        i = x;
        j = y;
        while (j >= 0 && i >= 0) {
            if (t[i][j] == 1) {
                return false;
            }
            i--;
            j--;
        }
        return true;

    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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