【leetcode刷题笔记】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.

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:

[
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]


题解:深度优先搜索,用一个List<Integer> cols保存当前棋盘的情况,cols.get(i)对应第i行(i=0,...n-1)皇后所在的列的索引(0,...,n-1)。几个函数的声明如下所示:

  1. private String[] PrintBoard(int n,List<Integer> cols):当搜索到一个答案的时候,根据cols将棋盘打印成题目要求的字符串数组的格式;
  2. private boolean isValid(List<Integer> cols,int col):当前的棋盘状态记录在cols中,需要在第cols.size()行col列放置一个皇后,该函数检查这种放置是否合理;
  3. private void QueenDfs(int n,int level,List<Integer> cols,List<String[]> result):深度优先搜索函数,level表示当前搜索到第level行,当level==n的时候,完成一次搜索;否则尝试将皇后放置在level行的0~n-1列,用isValid函数判断是否合理,如果合理,就放置皇后,并继续递归搜索棋盘下一行皇后放置的位置。
  4. public List<String[]> solveNQueens(int n):直接调用QueenDfs函数完成搜索。

代码如下:

 1 public class Solution {
 2     private String[] PrintBoard(int n,List<Integer> cols){
 3         String[] answer= new String[n];
 4         for(int i = 0;i < n;i++){
 5             StringBuffer temp = new StringBuffer();
 6             for(int j = 0;j < n;j ++){
 7                 temp.append(j == cols.get(i) ? "Q":".");
 8             }
 9             answer[i] = temp.toString();
10         }
11
12         return answer;
13     }
14     private boolean isValid(List<Integer> cols,int col){
15         for(int i = 0;i < cols.size();i++){
16             if(cols.get(i) == col)
17                 return false;
18             if(cols.size() - i == Math.abs(cols.get(i) - col))
19                 return false;
20         }
21         return true;
22     }
23     private void QueenDfs(int n,int level,List<Integer> cols,List<String[]> result){
24         if(level == n){
25             String[] s = PrintBoard(n,cols);
26             result.add(s);
27             return;
28         }
29
30         for(int i = 0;i < n;i++){
31             if(isValid(cols, i)){
32                 cols.add(i);
33                 QueenDfs(n, level+1, cols,result);
34                 cols.remove(cols.size()-1);
35             }
36         }
37     }
38     public List<String[]> solveNQueens(int n) {
39         List<String[]> result = new ArrayList<String[]>();
40         List<Integer> cols = new ArrayList<Integer>();
41         QueenDfs(n, 0, cols, result);
42
43         return result;
44     }
45 }

【leetcode刷题笔记】N-Queens

时间: 2024-12-21 12:08:02

【leetcode刷题笔记】N-Queens的相关文章

【leetcode刷题笔记】Sum Root to Leaf Numbers

Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. An example is the root-to-leaf path 1->2->3 which represents the number 123. Find the total sum of all root-to-leaf numbers. For example, 1 / 2 3 T

【leetcode刷题笔记】Longest Consecutive Sequence

Given an unsorted array of integers, find the length of the longest consecutive elements sequence. For example,Given [100, 4, 200, 1, 3, 2],The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4. Your algorithm should run in

【leetcode刷题笔记】Remove Duplicates from Sorted Array II

Follow up for "Remove Duplicates":What if duplicates are allowed at most twice? For example,Given sorted array A = [1,1,1,2,2,3], Your function should return length = 5, and A is now [1,1,2,2,3]. 题解: 设置两个变量:右边kepler和前向游标forward.如果当前kepeler所指的元素和

【leetcode刷题笔记】Restore IP Addresses

Given a string containing only digits, restore it by returning all possible valid IP address combinations. For example:Given "25525511135", return ["255.255.11.135", "255.255.111.35"]. (Order does not matter) 题解:深度优先搜索.用resul

【leetcode刷题笔记】Path Sum

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. For example:Given the below binary tree and sum = 22, 5 / 4 8 / / 11 13 4 / \ 7 2 1 return true, as t

【leetcode刷题笔记】Insertion Sort List

Sort a linked list using insertion sort. 题解:实现链表的插入排序. 要注意的地方就是,处理链表插入的时候尽量往当前游标的后面插入,而不要往前面插入,后者非常麻烦.所以每次利用kepeler.next.val和head.val比较大小,而不是kepeler.val和head.val比较大小,因为如果用后者,要把head指向的节点插入到kepeler指向的节点的前面,如果kepeler指向的节点是头结点,就更麻烦了. 代码如下: 1 /** 2 * Defi

【leetcode刷题笔记】Max Points on a Line

Given n points on a 2D plane, find the maximum number of points that lie on the same straight line. 题解: 思路比较简单,每条直线都可以表示为y=kx+b,所以对于任意三点,如果它们共线,那么它们中任意两点的斜率都相等. 所以就遍历points数组,对其中的每一个元素计算它和位于它后面的数组元素的斜率并保存在一个hashmap中. 这个hashmap的键就是两点构成直线的斜率,值就是和当前元素po

【leetcode刷题笔记】Spiral Matrix II

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. For example,Given n = 3, You should return the following matrix: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ] 题解:以前做过的Spiral Matrix是给一个矩阵螺旋式的输出,这道题是给一个n,螺旋式的

【leetcode刷题笔记】Set Matrix Zeroes

Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place. 题解:因为题目要求原地算法,所以我们只能利用矩阵第一行和第一列存放置零信息. 首先遍历第一行和第一列,看他们是否需要全部置零,用两个变量first_column_zero和first_row_zero来记录: 遍历矩阵,如果某个位置matrix[i][j]出现了0,就把matrix[i][0]和Matrix[0