52. N-Queens II

题目链接:https://leetcode.com/problems/n-queens-ii/description/
在刷完第一道题目 51. N-Queens 后,再看这道题就非常简单了,还是套用前一道题目的思路:

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

    public static void main(String[] args) {
        Solution s = new Solution();
        System.out.println(s.totalNQueens(4));
        System.out.println(s.totalNQueens(8));
    }

    public int totalNQueens(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] = '.';
            }
        }

        return dfs(board, 0);
    }


    private int dfs(char[][] board, int colIndex) {
        int res = 0;

        if (colIndex == board.length) {
            return 1;
        }
        for (int i = 0; i < board.length; i++) {
            if (validate(board, i, colIndex)) {
                board[i][colIndex] = 'Q';
                res += dfs(board, colIndex + 1);
                board[i][colIndex] = '.';
            }
        }
        return res;
    }

    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;
    }

}
posted @ 2018-03-07 18:07  optor  阅读(80)  评论(0编辑  收藏  举报