【LeetCode】52. 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.."]
]

 

描述:

n皇后问题,求可行解的个数

 

分析:

和上题(点这里)一样,但是返回的是可行解的个数

由于不需要保存棋盘,所以可以简化一部分代码

 

代码:

class Solution {
public:
	int totalNQueens(int n) {
		vector<string> chess;
		initChess(n, chess);
		vector<bool> visit(n, false);
		int result = 0;
		findSolution(n, 0, chess, visit, result);
		return result;
	}
	void initChess(int n, vector<string> &chess) {
		for (int i = 0; i < n; ++ i) {
			string row;
			for (int i = 0; i < n; ++ i) {
				row.push_back('.');
			}
			chess.push_back(row);
		}
	}
	void findSolution(int n, int row, vector<string> &chess, vector<bool> &visit, int &result) {
		if (row == n) {
			++ result;
			return ;
		}
		
		for (int column = 0; column < n; ++ column) {
			if (!visit[column] && diagonalSafe(chess, row, column)) {
				chess[row][column] = 'Q';
				visit[column] = true;
				findSolution(n, row + 1, chess, visit, result);
				chess[row][column] = '.';
				visit[column] = false;
			}
		}
	} 
	bool diagonalSafe(vector<string> &chess, int row, int column) {
		int row_count = chess.size(), column_count = chess[0].size();
		//主对角线
		for (int i = row + 1, j = column + 1; i < row_count && j < column_count; ++ i, ++ j) {
			if (chess[i][j] == 'Q') {
				return false;
			}
		}
		for (int i = row - 1, j = column - 1; i >= 0 && j >= 0; -- i, -- j) {
			if (chess[i][j] == 'Q') {
				return false;
			}
		}
		
		//副对角线
		for (int i = row + 1, j = column - 1; i < row_count && j >= 0; ++ i, -- j) {
			if (chess[i][j] == 'Q') {
				return false;
			}
		}
		for (int i = row - 1, j = column + 1; i >= 0 && j < column_count; -- i, ++ j) {
			if (chess[i][j] == 'Q') {
				return false;
			}
		}
		return true;
	}
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值