Follow up for N-Queens problem.
Now, instead outputting board configurations, return the totalnumber of distinct solutions.
经典算法值n后问题,
这题题给你一个n*n的棋盘,问你放置n个皇后共有多少种不用的放置方法,
这一一个典型的回溯法框架,并且也是很简单的一个回溯法框架,比这个更简单的就只有字符串全排列问题了。
这题使用深度优先遍历的回溯法解决,每一行只放一个皇后,每一列只放一个皇后,如何判断某个皇后是否和前面已经放置的皇后斜线冲突呢,使用abs(a-b)==abs(c-d),ac,bd分别为参与判断的两个皇后的横纵坐标,只要这个等式成立则这两个皇后一定斜线冲突
class Solution {
public:
int findRadius(vector<int>& houses, vector<int>& heaters) {
sort(houses.begin(), houses.end());
sort(heaters.begin(), heaters.end());
int index = 0; int m = -1;
for (int i = 0; i < houses.size(); i++)
{
while (index < heaters.size()&& heaters[index] < houses[i]) index++;
if (index == heaters.size()) m = max(m, houses[i] - heaters[index - 1]);
else if(index==0)
{
m = max(m, heaters[0] - houses[i]);
}
else
{
m = max(m, min(houses[i]-heaters[index-1],heaters[index]-houses[i]));
}
}
return m;
}
};