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.."]
]

 

代码:

class Solution {
public:
    bool isValid(int n, int i, int j, vector<int>& record, vector<string>& cur) {
		if(record[j])
			return false;
		for(int ii = i, jj = j; ii >= 0 && jj >= 0; ii--, jj--)
			if(cur[ii][jj] == 'Q')
				return false;
		for(int ii = i, jj = j; ii >= 0 && jj < n; ii--, jj++)
			if(cur[ii][jj] == 'Q')
				return false;
		return true;
	}
	void backSolver(int rest_n, int n, vector<string> cur, vector<int> record, int& res) {
		if(rest_n == n)
		{
			res++;
			return;
		}
		for(int i = 0; i<n; i++)
		{
			if(isValid(n, rest_n, i, record, cur))
			{
				cur[rest_n][i] = 'Q';
				record[i] = 1;
				backSolver(rest_n + 1, n, cur, record, res);
				cur[rest_n][i] = '.';
				record[i] = 0;
			}
		}
		return;
	}
	int totalNQueens(int n) {
        int res = 0;
		vector<string> cur;
		string cur_line = "";
		for(int i = 0; i<n; i++)
			cur_line += ".";
		for(int i = 0; i<n; i++)
			cur.push_back(cur_line);
		vector<int> record(n+1, 0);
		backSolver(0, n, cur, record, res);
		return res;
    }
};

 

题外话:

转眼属于巨蟹座的七月就过去了,这个月真的太快。有难忘的日子,有伙伴们的聚会,有激动到拉肚子的时刻,也有感冒的一天,恍恍惚惚,转眼就过去了。可能因为是夏天,所以日子总是格外地快。最值得吐苦水的,莫过于月初就看到希望的实验,到了月底,因为没有评估好的框架迁移,从而耗费了一个月的时间。当然,调参和各种trick是意外的收获。当然,也有因为这样莽撞的举措,才收获的很多信息源。anyway,感谢七月。感谢七月的快乐,感谢七月的忐忑,感谢七月的沮丧,也感谢七月发呆的时光。感谢七月雨后,路灯下的树荫倒影,感谢七月晚归的学子们。感谢奋战的K&K,感谢鱿小鱼和GUN神。感谢夜里的胡辣汤,感谢阳光,感谢雨天。一切一切,唯有感谢。

最近看电视剧,真的没想到会入坑,已经很久没有这样的感动和感触。好似一股热血,注入身心。就像无名之辈和The Archer唱着的那样,即使是不会被任何人记住,也不为了什么,只为让自己的理想和热血,不留遗憾。

再见,七月。你好,八月。

 

新的一个月,继续加油哦!

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值