[leetcode-in-go] 0052-N-Queens II

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 the number of distinct solutions to the n-queens puzzle.

Example:

Input: 4
Output: 2
Explanation: There are two distinct solutions to the 4-queens puzzle as shown below.
[
[".Q…", // Solution 1
“…Q”,
“Q…”,
“…Q.”],

["…Q.", // Solution 2
“Q…”,
“…Q”,
“.Q…”]
]

解题思路

  • 回溯
func available(current []int, index int) bool {
	n := len(current)
	for i, v := range current {
		// 同一列
		if index == v {
			return false
		}

		// 对角线
		if (n-i) == index-v || (n-i) == v-index {
			return false
		}
	}

	return true
}

func core(current []int, n int, cnt *int) {
	if len(current) == n {
        *cnt += 1
	}

	for i := 0; i < n; i++ {
		if available(current, i) {
			core(append(current, i), n, cnt)
		}
	}
}

func totalNQueens(n int) int {
    cnt := 0
	if n == 0 {
		return cnt
	}
	core([]int{}, n, &cnt)
	return cnt
}
发布了272 篇原创文章 · 获赞 93 · 访问量 39万+

猜你喜欢

转载自blog.csdn.net/shida_csdn/article/details/96370331
今日推荐