N-Queens
题目地址:
https://leetcode.com/problems/n-queens/description/
题目:
解题思路:
这题就是用传统的backtracking就可以。
代码:
https://leetcode.com/problems/n-queens/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.
For example,
There exist two distinct solutions to the 4-queens puzzle:
There exist two distinct solutions to the 4-queens puzzle:
[ [".Q..", // Solution 1 "...Q", "Q...", "..Q."], ["..Q.", // Solution 2 "Q...", "...Q", ".Q.."] ]
解题思路:
这题就是用传统的backtracking就可以。
代码:
public static void main(String[] args){ NQueens nQueens = new NQueens(); List<List<String>> rst = nQueens.solveNQueens(4); System.out.println(rst); } public List<List<String>> solveNQueens(int n) { List<List<String>> rst = new ArrayList<>(); char[][] board = new char[n][n]; for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ board[i][j] = '.'; } } dfs(board, 0, rst); return rst; } private void dfs(char[][] board, int row, List<List<String>> rst) { if(row == board.length){ rst.add(build(board)); return; } for(int col = 0; col <= board[0].length - 1; col++){ if(valid(row, col, board)){ board[row][col] = 'Q'; dfs(board, row + 1, rst); board[row][col] = '.'; } } } private List<String> build(char[][] board) { List<String> rst = new ArrayList<>(); for(int i = 0; i < board.length; i++){ String s = new String(board[i]); rst.add(s); } return rst; } private boolean valid(int x, int y, char[][] board) { for(int i = 0; i <= x - 1; i++){ for(int j = 0; j <= board.length - 1; j++){ if(board[i][j] == 'Q' && (j == y || (x - i == y - j || x - i == j - y))){ return false; } } } return true; }

Comments
Post a Comment