51. N-Queens

原题链接:https://leetcode.com/problems/n-queens/description/
这道题目就是由鼎鼎大名的八皇后问题延伸而来的 n 皇后问题,我看的《数据结构(C语言版)》上面树章节里面也提到了这个问题,说是使用典型的回溯法。这道题目本身我是没有想出解法的,官方也无解答,还是看了讨论区评分最高的答案。答案不好理解,还是自己放到 IDE 里面调试运行下就理解大致思路了:

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by clearbug on 2018/2/26.
 */
public class Solution {

    public static void main(String[] args) {
        Solution s = new Solution();
        List<List<String>> res4 = s.solveNQueens(4);
        List<List<String>> res8 = s.solveNQueens(8);
        System.out.println(s.solveNQueens(4));
        System.out.println(s.solveNQueens(8));
    }

    public List<List<String>> solveNQueens(int n) {
        char[][] board = new char[n][n];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                board[i][j] = '.';
            }
        }
        List<List<String>> res = new ArrayList<>();
        dfs(board, 0, res);
        return res;
    }

    private void dfs(char[][] board, int colIndex, List<List<String>> res) {
        if (colIndex == board.length) {
            res.add(construct(board));
            return;
        }
        for (int i = 0; i < board.length; i++) {
            if (validate(board, i, colIndex)) {
                board[i][colIndex] = 'Q';
                dfs(board, colIndex + 1, res);
                board[i][colIndex] = '.';
            }
        }
    }

    private boolean validate(char[][] board, int x, int y) {
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < y; j++) {
                if (board[i][j] == 'Q' && (x + j == y + i || x + y == i + j || x == i)) {
                    return false;
                }
            }
        }
        return true;
    }

    private List<String> construct(char[][] board) {
        List<String> res = new LinkedList<>();
        for (int i = 0; i < board.length; i++) {
            String s = new String(board[i]);
            res.add(s);
        }
        return res;
    }

}

这位老铁的答案算是勉强看懂了,百度百科的答案也不知道是谁贴的,真没看懂。。。

参考

https://baike.baidu.com/item/%E5%85%AB%E7%9A%87%E5%90%8E%E9%97%AE%E9%A2%98/11053477?fr=aladdin

posted @ 2018-03-07 17:22  optor  阅读(134)  评论(0编辑  收藏  举报