回溯法---八皇后/迷宫

下午在复习回溯法的一些相关概念,为了验证复习的效果,做了八皇后和迷宫问题进行验证。

八皇后:

#include 
#include 
#include 
#include 
using namespace std;

void helper(vector > >& res,vector >& tmp, vector >& maze, vector >& visited,vector >& 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 > 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 > directs = { {-1,0},{0,-1},{1,0},{0,1} };
	vector > tmp;
	vector > > res;
	int n = maze.size();
	vector > visited(n, vector(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 
#include 
#include 
#include 
using namespace std;

bool isProper(vector 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 >& res, vector& 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 > eightQueens(int n) {
	vector cur(n, string(n, '*'));
	vector > res;
	helper(res, cur, 0);
	return res;
}

int main() {
	vector > 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;
}

注意回溯法的流程和需要的判别条件~

你可能感兴趣的:(C++)