码迷,mamicode.com
首页 > 其他好文 > 详细

51 N-Queens

时间:2018-11-06 11:21:24      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:pre   bool   col   bec   func   ace   int   clear   about   

The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
?
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.







https://www.youtube.com/watch?v=Xa-yETqFNEQ
https://www.youtube.com/watch?v=xouin83ebxE&t=96s

https://leetcode.com/problems/n-queens/discuss/19805/My-easy-understanding-Java-Solution

好像是按照一列一列来填的


@Augustdoker The main idea here is to put Q in each column from left to right, and when we put Q in each column we check the validity row by row. Since we are traversing from left to right column, we only need to check whether the current position is in conflict with its left column elements. There are only three possible positions in the left column that might be in conflict with the current Q. Respectively, they are the 135 degree, horizontally left and 45 degree ones. For 135 degree, they are in a line whose slope is -1. So (y-j)/(x-i) = -1 -> y + x = i + j. For the horizontally one, x = i. And for the 45 degree one, the line slope is 1, so (y-j)/(x-i) = 1 -> y + i = x + j. Hope my explanation could be clear to you.


It also cost me half an hour to understand.?in the solution above, the Q‘s are put column by column, so you just check the left part of this board.?like:?for(int i=0; i<board.length; i++) {?for(int j=0; j<y; j++) {?to check if there is a Q on the left side in function validate()

then you check if there‘s a Q, the location u are about to put a Q (x,y) could be available, so it becomes:?(x-i==y-j | x==i | x-i==j-y)?the location can‘t on the east/ southeast/ northeast of Q?also, a plus is more effective than a minus?so it becomes:?(x+j == y+i || x==i || x+y==i+j)



// accepted 
class Solution {
    public List<List<String>> solveNQueens(int n) {
        // need to initalize a board 
        char[][] board = new char[n][n];
        // initalize the board with dots 
        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 col, List<List<String>> res){
        // base case 
        if(col == board.length){
            res.add(construct(board));
            return;
        }
        
        // else , do dfs
        for(int i = 0; i < board.length; i++){
            if(valid(i, col, board)){
                board[i][col] = ‘Q‘;
                dfs(board, col + 1, res);
                // backtrack
                board[i][col] = ‘.‘;
            }
        }
    }
    
    private boolean valid(int x, int y, char[][] board){
        // check three things with all the previous queens 
        // if the poteneial new queen is on the same row with any of the prev queens 
        // if ...................................... digonal 
        // if ........................................reverse digonal 
        for(int i = 0; i < board.length; i++){
            for(int j = 0; j < y; j++){
                if(board[i][j] == ‘Q‘ && (x == i || x - i == j - y || x - i == y - j)) return false;
            }
        }
        return true;
    }
    
    private List<String> construct(char[][] board){
        List<String> res = new ArrayList<>();
        for(char[] row : board){
            String newRow = new String(row);
            res.add(newRow);
        }
        return res;
    }
}

 

51 N-Queens

标签:pre   bool   col   bec   func   ace   int   clear   about   

原文地址:https://www.cnblogs.com/tobeabetterpig/p/9913247.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!