N-Queens

题目
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.

N-Queens_第1张图片
image

Given an integer n, return all distinct solutions to the n-queens puzzle.

Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively.

Example:

Input: 4
Output: [
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],

["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]
Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above.

答案

public class Solution {
    public static List solveNQueens(int n) {
        int[] place = new int[n];
        List list= new ArrayList();
        NQueens(list, place, 0, n);
        return list;
    }
    // k is for which row, the for loop below is for selecting a column
    public static void NQueens(List list, int[] place, int k, int n) {
        for(int i = 0; i < n; i++) {
            // Can we place a queen on kth row???
            if(isValidPlacement(place, k, i)) {
                // Yes please do so
                place[k] = i;
                
                // k is the last row, add the chessboard
                if(k == n - 1) {
                    // convert place to String[]
                    list.add(array2ChessBoard(place));
                }
                else {
                    // not yet, keep trying
                    NQueens(list, place, k + 1, n);
                }
            }
        }
        
    }
    public static boolean isValidPlacement(int[] place, int k, int i) {
        for(int j = 0; j < k; j++) {
            // look at previous k rows, do they have the same column as i?
            if(place[j] == i)
                return false;
            // if not the same column, could it be on the same diagonal(row diff == col diff)
            if(Math.abs(j - k) == Math.abs(place[j] - i))
                return false;
        }
        return true;
    }
    public static String[] array2ChessBoard(int[] place) {
        int n = place.length;
        String[] board = new String[n];
        for(int i = 0; i < n; i++) {
            board[i] = "";
            for(int j = 0; j < n; j++) {
                char c = (place[i] == j)? 'Q':'.';
                board[i] = board[i] + c;
            }
        }
        return board;
    }
}

你可能感兴趣的:(N-Queens)