回溯之电路布线

题目:一个起点到终点的路径,点的移动方向为上下左右,不能超出边界,一共有多少中路径,并列出所有路径。 (递归)

#include<iostream>
#include<vector>
#include<map>
#include<string>
#include<numeric>
using namespace std;
class node
{
public:
	node(int i = 0, int j = 0) :x(i), y(j) {};
	int x, y;
};
vector<vector<node>> res;
vector<vector<bool>> visit;
vector<vector<int>>res1;
int m, n;
int b[4][2] = {
	{-1,0},
	{0, 1},
	{1,0},
	{0,-1}
};
class solution
{
public:
	void test(node s,node e)
	{
		if (s.x==e.x && s.y == e.y)
			return;
		m = res1.size();
		n = res1[0].size();
		visit = vector<vector<bool>>(m,vector<bool>(n,false));
		vector<node>v;
		dfs(v, s, e);
		
	}
private:
	bool isrange(int x, int y)
	{
		if (x >= 0 && x < m&&y >= 0 && y < n)
			return true;
		else
			return false;
	}
	void dfs(vector<node>&v, node s, node e)
	{
		if (s.x == e.x&&s.y == e.y)
		{
			res.push_back(v);
			return;
		}
		v.push_back(s);
		visit[s.x][s.y] = 1;
		for (int i = 0; i < 4; i++)
		{
			int newx,newy;
			newx = s.x + b[i][0];
			newy = s.y + b[i][1];
			if (!isrange(newx, newy))
				continue;
			if (!visit[newx][newy])
			{
				node t;
				t.x = newx;
				t.y = newy;
				dfs(v, t, e);
			}
		}
		  visit[s.x][s.y] = 0;
		   v.pop_back();
	}

};
int main()
{
	class solution a;
	node s,e;
	s.x = 1;
	s.y = 1;
	e.x = 2;
	e.y = 2;
	res1 = vector<vector<int>>(3, vector<int>(3));
	a.test(s, e);
	for (int i = 0; i < res.size(); i++)
	{
		for (int j = 0; j < res[i].size(); j++)
			cout << "( " << res[i][j].x << " ,  " << res[i][j].y << ")" << " ";
		cout << endl;
	}
	system("pause");
	return 0;
}

题目:电路布线(dfs)

#include<iostream>
#include<vector>
#include<map>
#include<string>
#include<numeric>
using namespace std;
class node
{
public:
	node(int i = 0, int j = 0) :x(i), y(j) {};
	int x, y;
};
vector<vector<node>> res;
vector<vector<bool>> visit;
vector<vector<int>>grid;
int m, n;
int b[4][2] = {
	{-1,0},
	{0, 1},
	{1,0},
	{0,-1}
};
class solution
{
public:
	void test(node s,node e)
	{
		if (s.x==e.x && s.y == e.y)
			return;
		m = grid.size();
		n = grid[0].size();
		visit = vector<vector<bool>>(m,vector<bool>(n,false));
		vector<node>v;
		dfs(v, s, e);	
	}
private:
	bool isrange(int x, int y)
	{
		if (x >= 0 && x < m&&y >= 0 && y < n)
			return true;
		else
			return false;
	}
	void dfs(vector<node>&v, node s, node e)
	{
		if (s.x == e.x&&s.y == e.y)
		{
			res.push_back(v);
			return;
		}
		v.push_back(s);
		visit[s.x][s.y] = 1;
		for (int i = 0; i < 4; i++)
		{
			int newx,newy;
			newx = s.x + b[i][0];
			newy = s.y + b[i][1];
			if (grid[newx][newy] == 1 && !isrange(newx, newy))
				continue;
			if (!visit[newx][newy])
			{
				node t;
				t.x = newx;
				t.y = newy;
				dfs(v, t, e);
			}
		}
		  visit[s.x][s.y] = 0;
		   v.pop_back();
	}
};
发布了98 篇原创文章 · 获赞 1 · 访问量 4492

猜你喜欢

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