所有可能的路径

给你一个有 n 个节点的 有向无环图(DAG),请你找出所有从节点 0 到节点 n-1 的路径并输出(不要求按特定顺序)。二维数组的第 i 个数组中的单元都表示有向图中 i 号节点所能到达的下一些节点,空就是没有下一个结点了。

 

头文件中:

/*深度优先搜索*/
#include<vector>
#include<iostream>
#include<string>
class Solution {
public:
	Solution();//构造函数
	~Solution() {}//析构函数
	vector<vector<int>> ans;
	vector<int> stk;

	void dfs(vector<vector<int>>& graph, int x, int n) {
		if (x == n) {
			ans.push_back(stk);
			return;
		}
		for (auto& y : graph[x]) {
			stk.push_back(y);
			dfs(graph, y, n);
			stk.pop_back();
		}
	}

	vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) {
		stk.push_back(0);
		dfs(graph, 0, graph.size() - 1);
		return ans;
	}
};

上述主要用到递归的思想。
源文件中:

#include"1.h"//包含刚刚的头文件
Solution::Solution()
{
	vector<vector<int>> jxqhhh;
	vector<vector<int>> graph = { {1, 2}, {3}, {3}, {} };
	cout << "图为:" << endl;
	for (int i = 0; i < graph.size(); i++)
	{
		for (int j = 0; j < graph[i].size(); j++)
			cout << graph[i][j] << " ";
		cout << endl;
	}
	cout << "路径为:" << endl;
	jxqhhh =allPathsSourceTarget(graph);
	for (int i = 0; i < jxqhhh.size(); i++)
	{
		int num = jxqhhh[i].size();
		for (int j = 0; j < num; j++)
			cout << jxqhhh[i][j] << " ";
		cout << endl;
	}
}

main.cpp中:

using namespace std;
#include"1.h"
void main()
{
	Solution jxq = Solution();//构造实例
}

 运行结果:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值