首页 > 其他分享 >【刷题笔记】51. N-Queens

【刷题笔记】51. N-Queens

时间:2023-09-15 13:33:06浏览次数:31  
标签:index prev string res 51 Queens 刷题 dia2 row

题目

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.

题目大意

给定一个整数 n,返回所有不同的 n 皇后问题的解决方案。每一种解法包含一个明确的 n 皇后问题的棋子放置方案,该方案中 'Q' 和 '.' 分别代表了皇后和空位。

解题思路

  • 求解 n 皇后问题
  • 利用 col 数组记录列信息,col 有 n 列。用 dia1,dia2 记录从左下到右上的对角线,从左上到右下的对角线的信息,dia1 和 dia2 分别都有 2*n-1 个。
  • dia1 对角线的规律是 i + j 是定值,例如[0,0],为 0;[1,0]、[0,1] 为 1;[2,0]、[1,1]、[0,2] 为 2;
  • dia2 对角线的规律是 i - j 是定值,例如[0,7],为 -7;[0,6]、[1,7] 为 -6;[0,5]、[1,6]、[2,7] 为 -5;为了使他们从 0 开始,i - j + n - 1 偏移到 0 开始,所以 dia2 的规律是 i - j + n - 1 为定值
  • 还有一个位运算的方法,每行只能选一个位置放皇后,那么对每行遍历可能放皇后的位置。如何高效判断哪些点不能放皇后呢?这里的做法毕竟巧妙,把所有之前选过的点按照顺序存下来,然后根据之前选的点到当前行的距离,就可以快速判断是不是会有冲突。举个例子: 假如在 4 皇后问题中,如果第一二行已经选择了位置 [1, 3],那么在第三行选择时,首先不能再选 1, 3 列了,而对于第三行, 1 距离长度为2,所以它会影响到 -1, 3 两个列。同理,3 在第二行,距离第三行为 1,所以 3 会影响到列 2, 4。由上面的结果,我们知道 -1, 4 超出边界了不用去管,别的不能选的点是 1, 2, 3,所以第三行就只能选 0。在代码实现中,可以在每次遍历前根据之前选择的情况生成一个 occupied 用来记录当前这一行,已经被选了的和由于之前皇后Hit范围所以不能选的位置,然后只选择合法的位置进入到下一层递归。另外就是预处理了一个皇后放不同位置的字符串,这样这些字符串在返回结果的时候是可以在内存中复用的,省一点内存。

参考代码

package leetcode

// 解法一 DFS
func solveNQueens(n int) [][]string {
	col, dia1, dia2, row, res := make([]bool, n), make([]bool, 2*n-1), make([]bool, 2*n-1), []int{}, [][]string{}
	putQueen(n, 0, &col, &dia1, &dia2, &row, &res)
	return res
}

// 尝试在一个n皇后问题中, 摆放第index行的皇后位置
func putQueen(n, index int, col, dia1, dia2 *[]bool, row *[]int, res *[][]string) {
	if index == n {
		*res = append(*res, generateBoard(n, row))
		return
	}
	for i := 0; i < n; i++ {
		// 尝试将第index行的皇后摆放在第i列
		if !(*col)[i] && !(*dia1)[index+i] && !(*dia2)[index-i+n-1] {
			*row = append(*row, i)
			(*col)[i] = true
			(*dia1)[index+i] = true
			(*dia2)[index-i+n-1] = true
			putQueen(n, index+1, col, dia1, dia2, row, res)
			(*col)[i] = false
			(*dia1)[index+i] = false
			(*dia2)[index-i+n-1] = false
			*row = (*row)[:len(*row)-1]
		}
	}
	return
}

func generateBoard(n int, row *[]int) []string {
	board := []string{}
	res := ""
	for i := 0; i < n; i++ {
		res += "."
	}
	for i := 0; i < n; i++ {
		board = append(board, res)
	}
	for i := 0; i < n; i++ {
		tmp := []byte(board[i])
		tmp[(*row)[i]] = 'Q'
		board[i] = string(tmp)
	}
	return board
}

// 解法二 二进制操作法 Signed-off-by: Hanlin Shi [email protected]
func solveNQueens2(n int) (res [][]string) {
	placements := make([]string, n)
	for i := range placements {
		buf := make([]byte, n)
		for j := range placements {
			if i == j {
				buf[j] = 'Q'
			} else {
				buf[j] = '.'
			}
		}
		placements[i] = string(buf)
	}
	var construct func(prev []int)
	construct = func(prev []int) {
		if len(prev) == n {
			plan := make([]string, n)
			for i := 0; i < n; i++ {
				plan[i] = placements[prev[i]]
			}
			res = append(res, plan)
			return
		}
		occupied := 0
		for i := range prev {
			dist := len(prev) - i
			bit := 1 << prev[i]
			occupied |= bit | bit<<dist | bit>>dist
		}
		prev = append(prev, -1)
		for i := 0; i < n; i++ {
			if (occupied>>i)&1 != 0 {
				continue
			}
			prev[len(prev)-1] = i
			construct(prev)
		}
	}
	construct(make([]int, 0, n))
	return
}

标签:index,prev,string,res,51,Queens,刷题,dia2,row
From: https://blog.51cto.com/u_16110811/7480331

相关文章

  • 洛谷 P9518 queue
    一眼模拟。需要维护的东西可以根据操作求得:start:正在玩游戏的\(1\)或\(2\)个人;arrive:当前在排队但没玩游戏的队列、每个人是否在排队、游玩;leave:每个人是否在排队、游玩。如何维护正在玩游戏的人:我们使用\(p_1\)、\(p_2\)两变量存储,优先保证\(p_1\)有值,当\(p_1......
  • P251——用RadialGradientBrush填充椭圆,并进行RotateTransform变换
    一、认识RadialGradientBrush(径向渐变)    1.坐标      RadialGradientBrush可以用来填充矩形(正方形)和椭圆(正圆),      填充区域使用比例坐标,      椭圆的坐标(0,0)和(1,1)构成的矩形内切于椭圆2.设置径向渐变颜色GradientStop<Gradi......
  • 代码随想录算法训练营第8天| ● 344.反转字符串 ● 541. 反转字符串II ● 剑指Offer 0
    344.反转字符串mydemo--(一次就过)--(成功)classSolution{public:voidreverseString(vector<char>&s){intlen=s.size();chartmp;inti=0;intj=len-1;while(i<j){tmp=s[i];......
  • 【刷题笔记】50. Pow
    题目Implement pow(x, n),whichcalculates x raisedtothepower n (xn).Example1:Input:2.00000,10Output:1024.00000Example2:Input:2.10000,3Output:9.26100Example3:Input:2.00000,-2Output:0.25000Explanation:2-2=1/22=1/4=0.25N......
  • keil51的STARTUP.A51
     翻译后的STARTUP.A51:$NOMOD51;Ax51宏汇编器控制命令,禁止预定义的8051。使编译器不使能预定义的;8051符号,避免产生重复定义的错误。;------------------------------------------------------------------------------;该文件是C51编译器包的一部分;版权所有(c)1988-2005Kei......
  • CF510C
    其实是一道板子题,建议评黄。题意求一种满足让\(n\)个字符串合法排列的字典序。思路不难想到使用拓扑排序。具体地说,我们可以把字符串当作点,若有两个字符串\(s1,s2\)且满足\(s1\)的字典序小于\(s2\),则建一条从\(s1\)到\(s2\)的边。注意到如果有两个字符串\(s2\)......
  • 【刷题笔记】48. Rotate Image
    题目Youaregivenan n x n 2Dmatrixrepresentinganimage.Rotatetheimageby90degrees(clockwise).Note:Youhavetorotatetheimage in-place,whichmeansyouhavetomodifytheinput2Dmatrixdirectly. DONOT allocateanother2Dmatrixanddot......
  • 牛客刷题
    #include<stdio.h>intmain(intargc,charconst*argv[]){intk=2000;inti=0;while(k>1){i++;k=k>>1;printf("i=%dk=%d\n",i,k);}printf("%d\n",i);......
  • 华为认证从哪学起?刷刷题就可以了!
    大家好!今天我要和大家分享一个非常重要的考试技巧——刷题!无论你是刚刚踏入职场还是已经有一定工作经验的人,华为认证都是提升自己竞争力的一条捷径。那么,从哪里开始学习华为认证呢?我告诉你,刷题是一个很好的起点!华为认证是IT行业中备受认可的证书,尤其是华为HCIP认证。它不仅能够证明......
  • LED汽车灯驱动芯片降压恒流IC内置mos管AP5193
    AP5193是一款PWM工作模式,高效率、外围简单、内置功率MOS管,适用于4.5-100V输入的高精度降压LED恒流驱动芯片。最大电流2.5A。AP5193可实现线性调光和PWM调光,线性调光脚有效电压范围0.55-2.6V.AP5193工作频率可以通过RT外部电阻编程来设定,同时内置抖频电路,可以降低对其他设备的E......