回溯法之马周游

 

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
vector<vector<bool>> visit;
int b[8][2] = {
	{-1,-2},
	{-1,2},
	{1,-2},
	{1,2},
	{-2,-1},
	{-2,1},
	{2,-1},
	{2,1}
};
int n;
class node
{
public:
	node(int x, int y) :x(x), y(y) {};
	node() {};
	int x, y;
};
vector<vector<node>> res;
class solution
{
public:
	void test(int x,int y)
	{
		node t(x, y);
		vector<node> v;
		dfs(t, v);
		cout << res.size();
	}
private:
	bool isTrue(int x, int y)
	{
		if (x < 0 || x >= n || y < 0 || y >= n)
			return false;
		return true;
	}
	bool isfull(vector<vector<bool>> visit)
	{
		for (int i = 0; i < n; i++)
			for (int j = 0; j < n; j++)
				if (visit[i][j])
					return false;
		return true;
	}
	void dfs(node s, vector<node>v)
	{
		static int count = 0;
		if (count==n*n-1)
		{
			v.push_back(s);
			res.push_back(v);
			return;
		}
		int x, y;
		x = s.x;
		y = s.y;
		visit[x][y] = true;
		v.push_back(s);
		for (int i = 0; i < 8; i++)
		{
			int nx, ny;
			nx = x + b[i][0];
			ny = y + b[i][1];
			if (isTrue(nx, ny) && !visit[nx][ny])
			{
				count++;
				node t(nx,ny);
				dfs(t,v);
			}
		}
		   visit[x][y] = false;
		res.pop_back();
		--count;
	}

};
发布了98 篇原创文章 · 获赞 1 · 访问量 4483

猜你喜欢

转载自blog.csdn.net/weixin_40823740/article/details/103567430