#
Title
Difficulty
Topic
51
N-Queens
Hard
Backtracking
Description
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:
1 2 3 4 5 6 7 8 9 10 11 12 13
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.
Backtracking
LeetCode 51. N-Queens - 花花酱 刷题找工作 EP41 视频里讲的很清晰。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
class { 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; } public void dfs (char [][] board, int row, List<List<String>> res) { int n = board.length; if (row == n) { List<String> tmp = new ArrayList<>(); for (int i=0 ; i<n; i++) { tmp.add(new String(board[i])); } res.add(tmp); return ; } for (int j=0 ; j<n; j++) { if (isValid(board, row, j)) { board[row][j] = 'Q' ; dfs(board, row+1 , res); board[row][j] = '.' ; } } } public boolean isValid (char [][] board, int row, int col) { int n = board.length; for (int j=0 ; j<n; j++) { if (board[j][col] != '.' ) return false ; if (row+col-j >= 0 && row+col-j < n && board[row+col-j][j] != '.' ) return false ; if (row-col+j >= 0 && row-col+j < n && board[row-col+j][j] != '.' ) return false ; } return true ; } }
近期评论