下午在复习回溯法的一些相关概念,为了验证复习的效果,做了八皇后和迷宫问题进行验证。
八皇后:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
void helper(vector<vector<pair<int,int> > >& res,vector<pair<int, int> >& tmp, vector<vector<int> >& maze, vector<vector<bool> >& visited,vector<pair<int,int> >& directs, int i, int j) {
if (i < 0 || j < 0 || i >= maze.size() || j >= maze.size()) return;
if (i == maze.size() - 1 && j == maze.size() - 1) {
tmp.push_back(make_pair(i, j));
res.push_back(tmp);
return;
}
if (visited[i][j] || maze[i][j]) return;
visited[i][j] = true;
tmp.push_back(make_pair(i, j));
for (auto direct : directs) {
int x = i + direct.first, y = j + direct.second;
helper(res,tmp, maze, visited, directs, x, y);
}
tmp.pop_back();
visited[i][j] = false;
}
int main() {
vector<vector<int> > maze =
{ { 0,0,0,0,0 },
{ 0,1,0,1,0 },
{ 0,1,1,0,0 },
{ 0,1,1,0,1 },
{ 0,0,0,0,0 } };
vector<pair<int, int> > directs = { {-1,0},{0,-1},{1,0},{0,1} };
vector<pair<int, int> > tmp;
vector<vector<pair<int, int> > > res;
int n = maze.size();
vector<vector<bool> > visited(n, vector<bool>(n, false));
helper(res, tmp, maze, visited, directs, 0, 0);
for (auto rs : res) {
for (auto itm : rs) {
cout << itm.first << " " << itm.second << endl;
}
cout << "------------------" << endl;
}
return 0;
}
N皇后
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;
bool isProper(vector<string> tmp, int rows, int cols) {
for (int i = 0; i < rows; i++) {
if (tmp[i][cols] == '+') return false;
}
for (int i = 0; i < cols; i++) {
if (tmp[rows][i] == '+') return false;
}
for (int i = rows - 1, j = cols - 1; i >= 0 && j >= 0; i--, j--) {
if (tmp[i][j] == '+') return false;
}
for (int i = rows - 1, j = cols + 1; i >= 0 && j < tmp.size(); i--, j++) {
if (tmp[i][j] == '+') return false;
}
return true;
}
void helper(vector<vector<string> >& res, vector<string>& tmp, int i) {
if (i >= tmp.size()) {
res.push_back(tmp);
return;
}
for (int j = 0; j < tmp.size(); j++) {
if (isProper(tmp, i, j)) {
tmp[i][j] = '+';
helper(res, tmp, i + 1);
tmp[i][j] = '*';
}
}
}
vector<vector<string> > eightQueens(int n) {
vector<string> cur(n, string(n, '*'));
vector<vector<string> > res;
helper(res, cur, 0);
return res;
}
int main() {
vector<vector<string> > res=eightQueens(8);
cout << res.size() << endl;
for (auto rs : res) {
for (auto itm : rs) {
for (auto c : itm) {
cout << c << " ";
}
cout << endl;
}
cout << "----------" << endl;
}
return 0;
}
注意回溯法的流程和需要的判别条件~