leetcode51. N皇后

class Solution {
public:
	vector<vector<string>> solveNQueens(int n) {
		N = n; 
		vector<string> col(n, string(n, '.'));
		dfs(-1, col);
		return _ret;
	}

	void dfs(int i, vector<string>& col)
	{
		if (i == N - 1)
		{
#ifdef PRINT
			cout << ++cnt << "===\n";
			for (auto v : col)
			{
				cout << v << "\n";
			}
			cout << "\n";
#endif

			_ret.push_back(col);
		}
		else
		{			
			for (size_t j = 0; j < N; j++)
			{				
				col[i + 1] = string(N, '.');
				col[i+1][j] = 'Q';

				if(isPromise(i+1, j, col))
				dfs(i + 1, col);
			}
		}
	}

	bool isPromise(int i, int j, vector<string>& col)
	{
		for (int k = 0; k < i; k++)
		{
			if (col[k][j] == col[i][j])
			{
				return false;
			}

			int d = abs(i - k);
			if (  (j -d >= 0 && col[i][j] == col[k][ abs( j-d )])  
				|| (j + d < col.size() && col[i][j] == col[k][j + d]) )
			{
				return false;
			}
		}
				
		return true;
	}

	int N;
	int cnt = 0;
	vector<vector<string>> _ret;
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值