leetcode 刷题之路 94 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.."]
]

非常经典的N皇后问题:在一个N*N的棋盘上放置N个皇后,每行一个并使其不能互相攻击(同一行、同一列、同一对角线上的皇后都会自动攻击)。

采用回溯来解决这个问题。

回溯法解决的问题都可以用枚举法解决,对于E中的任意一个元祖,逐个检查其是否满足约束集D,如果满足,就为问题的一个解,枚举法的缺点在于计算量大,而回溯法在搜索过程中,一旦发现原先的选择并不优或者达不到目标,立即回溯到前一步重新选择,简单的说,回溯法的思想就是-此路不通,掉头重新选路,这样能够避免无效搜索,降低了算法复杂度。

回溯法解决问题的一般思路为:

(1)针对所给问题,定义问题的解空间;

(2)确定易于搜索的解空间结构;

(3)以深度优先方式搜索解空间,并在搜索过程中用剪枝函数避免无效搜索。

N皇后的问题可以这样求解,从上至下依次在每一行放置皇后,进行搜索,若在某一行的任意一列放置皇后均不能满足要求,则不再向下搜索,而进行回溯,回溯至有其他列可放置皇后的一行,再向下搜索,直到搜索至最后一行,找到可行解,输出。

Accepted Solution:

class Solution {
 public:
	 vector<vector<string> > solveNQueens(int n)
	 {
		 vector<vector<string>> res;
		 vector<string> board(n, string(n, '.'));
			 helper(res, board, 0, n);
		return res;
	 }
	 void helper(vector<vector<string>> &res, vector<string> &board, int row, int n)
	 {
		 if (row == n)
			 res.push_back(board);
		 for (int clmn = 0; clmn<n; clmn++)
		 {
			 if (isValid(board, row, clmn,n))
			 {
				 board[row][clmn] = 'Q';
				 helper(res, board, row + 1, n);
				 board[row][clmn] = '.';
			 }
		 }
	 }
	 bool isValid(vector<string> &board, int row, int clmn, int n)
	 {
		 for (int i = 0; i<n; i++)
		 if (board[i][clmn] == 'Q')
			 return false;
		 for (int i = 0; i<n; i++)
		 if ((i + row - clmn) >= 0 && (i + row - clmn) < n && board[i + row - clmn][i] == 'Q')
			 return false;
		 for (int i = 0; i<n; i++)
		 if ((i + row + clmn - n + 1) >= 0 && (i + row + clmn - n + 1) < n && board[i + row + clmn - n + 1][n-1-i] == 'Q')
			 return false;
		 return true;
	 }
 };

leetcode 刷题之路 94 N-Queens

时间: 2024-11-02 13:22:25

leetcode 刷题之路 94 N-Queens的相关文章

leetcode 刷题之路 63 Binary Tree Zigzag Level Order Traversal

Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between). For example: Given binary tree {3,9,20,#,#,15,7}, 3 / 9 20 / 15 7 return its zig

leetcode 刷题之路 64 Construct Binary Tree from Inorder and Postorder Traversal

Given inorder and postorder traversal of a tree, construct the binary tree. Note: You may assume that duplicates do not exist in the tree. 给出二叉树的中序遍历和后序遍历结果,恢复出二叉树. 后序遍历序列的最后一个元素值是二叉树的根节点的值,查找该元素在中序遍历序列中的位置mid,根据中序遍历和后序遍历性质,有: 位置mid以前的序列部分为二叉树根节点左子树中

leetcode 刷题之路 92 Climbing Stairs

You are climbing a stair case. It takes n steps to reach to the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? 一个台阶总共有n级,如果一次可以跳1级,也可以跳2级,求总共有多少总跳法. 分析: 一次最多只能跳两级,那么对于第n级(n>=2)台阶,显然只能从第n-1级跳一级到达或

leetcode 刷题之路 93 Merge k Sorted Lists

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. 将k个有序链表合并成一个有序链表. 思路,之前做过两个有序链表的合并操作,对于k个链表,我们最先想到的就是能不能转化为我们熟悉的两个链表的合并,可以我们先将k个链表分为两部分,先对这两部分完成链表的有序合并操作,再对合并得到的两个链表进行合并,这是一个递归性质的描述,采用递归很容易实现这个程序,和数组

leetcode 刷题之路 70 earch Insert Position 二分查找插入位置

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You may assume no duplicates in the array. Here are few examples. [1,3,5,6], 5 → 2 [1,3,5,6], 2

leetcode 刷题之路 95 N-Queens I

Follow up for N-Queens problem. Now, instead outputting board configurations, return the total number of distinct solutions. N皇后问题的变种,要求直接输出N皇后的解法数目.这道题可以在N-Queens I的基础上增加计数功能,在每求得一个成功的解时(行数为N时)使计数变量递增即可.题目不要求输出具体的解法,因此可以做一点优化,使用position数组用来表示皇后的位置,p

leetcode 刷题之路 76 Remove Duplicates from Sorted List

Given a sorted linked list, delete all duplicates such that each element appear only once. For example, Given 1->1->2, return 1->2. Given 1->1->2->3->3, return 1->2->3. 删除排序链表中重复的节点,删除操作完成后,原链表中的重复节点只保留一个. 思路,遍历链表,如果当前节点和下一个节点重复

leetcode 刷题之路 66 Path Sum II

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. For example: Given the below binary tree and sum = 22, 5 / 4 8 / / 11 13 4 / \ / 7 2 5 1 return [ [5,4,11,2], [5,8,4,5] ] 给定一个二叉树和数字sum,输出二叉树中从根节点到

leetcode 刷题之路 77 Permutations II

Given a collection of numbers that might contain duplicates, return all possible unique permutations. For example, [1,1,2] have the following unique permutations: [1,1,2], [1,2,1], and [2,1,1]. Permutations 的升级版,依旧是全排列问题,但是序列中可能会出现重复数字. 思路:采用字典序的非递归方