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

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

八皇后:

#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;
}

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值