51. N-Queens

这是一道很经典的题目,相信很多程序员都知道。

其实解题的思路很简单,就是在每行枚举选择每个位置,判断选则的位置是否符合要求。如果符合要求,继续在下一行按照这个方法进行;如果不符合,枚举试验当前行下一个位置,当前行如果所有位置都有冲突,则返回上一行选择上一行下一个合适的位置。

其实就是典型的深度优先搜索的思路。自己的解题思路,整个棋盘当前摆放的情况通过一个二维数组int[][] chess表示;判断当前选的位置是否合法,只需要判断它之前的两个斜线方向和直线方向是否已放置过皇后;用List<Integer>记录每个方案,最后再转为List<List<String>>,可以避免搜索过程中处理字符串的复杂步骤。下面是代码:

int n;
public List<List<String>> solveNQueens(int n) {
    List<List<String>> res = new ArrayList<>();
    if (n <= 0) {
        return res;
    }

    this.n = n;
    //只记录每行存放的点
    List<List<Integer>> paths = new ArrayList<>();
    //用一个chess数组记录当前摆放的情况
    int[][] chess = new int[n][n];

    helper(0, new ArrayList<>(), paths, chess);

    return convert(paths);
}

public void helper(int row, List<Integer> path, List<List<Integer>> paths, int[][] chess) {
    if (row == n) {
        paths.add(new ArrayList<>(path));
        return;
    }

    for (int col = 0; col < n; col++) {
        if (!isValid(row, col, chess)) {
            continue;
        }
        chess[row][col] = 1;
        path.add(col);
        helper(row + 1, path, paths, chess);
        chess[row][col] = 0;
        path.remove(path.size() - 1);
    }
}

public boolean isValid(int row, int col, int[][] chess) {
    if (row < 0 || row >= chess.length || col < 0 || col >= chess.length || chess[row][col] == 1) {
        return false;
    }

    for (int i = row - 1; i >= 0; i--) {
        if (chess[i][col] == 1) {
            return false;
        }
    }

    for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) {
        if (chess[i][j] == 1) {
            return false;
        }
    }

    for (int i = row - 1, j = col + 1; i >= 0 && j < chess.length; i--, j++) {
        if (chess[i][j] == 1) {
            return false;
        }
    }

    return true;
}

public List<List<String>> convert(List<List<Integer>> resi) {
    List<List<String>> ress = new ArrayList<>();
    if (resi == null || resi.size() == 0) {
        return ress;
    }

    for (int i = 0; i < resi.size(); i++) {
        List<String> subres = new ArrayList<>();
        for (int j = 0; j < resi.get(i).size(); j++) {
            StringBuffer buffer = new StringBuffer();
            for (int k = 0; k < n; k++) {
                if (k == resi.get(i).get(j)) {
                    buffer.append('Q');
                } else {
                    buffer.append('.');
                }
            }
            subres.add(buffer.toString());
        }
        ress.add(subres);
    }

    return ress;
}

看了leetcode上discuss上的解法,有两个部分处理的更优:
1、整个棋盘的状态通过一个char[][]数组记录,这样最后直接把char数组转为List<List<String>>即可,比自己的方法节省了一个paths的空间。
2、判断每个位置是否合法的函数,巧妙的通过坐标值的计算判断。
第一个优点体现的是选择合适的数据结构的能力;第二个优点体现的是对题目全面洞察并进行条件转换的能力。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 原题 n皇后问题是将n个皇后放置在n*n的棋盘上,皇后彼此之间不能相互攻击。给定一个整数n,返回所有不同的n皇后问...
    Jason_Yuan阅读 2,109评论 0 0
  • 题目 The n-queens puzzle is the problem of placing n queens...
    Al73r阅读 264评论 0 0
  • 不知道简书搞什么。。刚才编辑了一下这个文章(原本是3.4写的),结果更新之后URL失效了,怎么也找不到了。。还好之...
    DrunkPian0阅读 239评论 0 0
  • 这题是dfs套路,按照常理想的话我们需要一个存储坐标的数据结构,但这题只要一个一维数组就够了,因为n皇后的横坐标正...
    DrunkPian0阅读 305评论 0 0
  • 题目 The n-queens puzzle is the problem of placing n queens...
    persistent100阅读 363评论 0 0