0
点赞
收藏
分享

微信扫一扫

6道经典递归、回溯、分治相关题目-N皇后问题

龙驹书房 2022-07-27 阅读 62


6道经典递归、回溯、分治相关题目-N皇后问题_leetcode


6道经典递归、回溯、分治相关题目-N皇后问题_i++_02


6道经典递归、回溯、分治相关题目-N皇后问题_i++_03


6道经典递归、回溯、分治相关题目-N皇后问题_leetcode_04


6道经典递归、回溯、分治相关题目-N皇后问题_i++_05


6道经典递归、回溯、分治相关题目-N皇后问题_leetcode_06

class Solution {
public:
vector<vector<string>> result;
int** isValid;
int* pos;

void Sub(int s, int n)
{
if (s > n)
{
vector<string> ans;
string str = "";
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
if (j == pos[i])
str += "Q";
else
str += ".";
ans.push_back(str);
str = "";
}
result.push_back(ans);
return;
}
else for (int i = 0; i < n; i++)
if (!isValid[s-1][i])
{
pos[s-1] = i;
for (int j = s; j < n; j++)
{
isValid[j][i]++;
}
int x = s;
int y = i-1;
while (x < n && y >= 0)
{
isValid[x][y]++;
x++;
y--;
}
x = s;
y = i+1;
while (x < n && y < n)
{
isValid[x][y]++;
x++;
y++;
}

//Next Step
Sub(s+1,n);

for (int j = s; j < n; j++)
{
isValid[j][i]--;
}
x = s;
y = i-1;
while (x < n && y >= 0)
{
isValid[x][y]--;
x++;
y--;
}
x = s;
y = i+1;
while (x < n && y < n)
{
isValid[x][y]--;
x++;
y++;
}
}
}

vector<vector<string>> solveNQueens(int n) {
isValid = new int* [n];
pos = new int [n];
for (int i = 0; i < n; i++)
{
isValid[i] = new int [n];
for (int j = 0; j < n; j++)
isValid[i][j] = 0;
}
Sub(1, n);
return result;
}
};


举报

相关推荐

0 条评论