算法训练营|图论第一天 98. 所有可达路径

题目:所有可到达路径

题目链接:

98. 所有可达路径 (kamacoder.com)

解题思路:

邻接矩阵,注意没有result == -1时候特判

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;
vector<vector<int>>result;
vector<int>path;
void dfs(vector<vector<int>>grid, int x, int n) {
	if (x == n) {
		result.push_back(path);
		return;
	}
	for (int i = 1; i <= n; i++) {
		if (grid[x][i] == 1) {
			path.push_back(i);
			dfs(grid, i, n);
			path.pop_back();
		}
	}
}
int main() {
	int n, m;
	cin >> n >> m;
	vector<vector<int>>grid(n + 1, vector<int>(n + 1, 0));
	while (m--) {
		int s, t;
		cin >> s >> t;
		grid[s][t] = 1;
	}
	path.push_back(1);
	dfs(grid, 1, n);
	if (result.size() == 0) cout << -1 << endl;
	for (int i = 0; i < result.size(); i++) {
		for (int j = 0; j < result[i].size() - 1; j++) {
			cout << result[i][j] << ' ';
		}
		cout << result[i][result[i].size() - 1]<<endl;
	}
}

邻接表的写法:

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;
vector<vector<int>>result;
vector<int>path;
void dfs(vector<list<int>>grid, int x, int n) {
	if (x == n) {
		result.push_back(path);
		return;
	}
	for (auto i : grid[x]) {
		path.push_back(i);
		dfs(grid, i, n);
		path.pop_back();
	}
}
int main() {
	int n, m;
	cin >> n >> m;
	vector<list<int>>grid(n + 1);
	while (m--) {
		int s, t;
		cin >> s >> t;
		grid[s].push_back(t);
	}
	path.push_back(1);
	dfs(grid, 1, n);
	if (result.size() == 0) {
		cout << -1 << endl;
	}
	for (auto path : result) {
		for (int i = 0; i < path.size() - 1; i++) {
			cout << path[i] << ' ';
		}
		cout << path[path.size() - 1] << endl;
	}
	return 0;
}
相关推荐
A_nanda6 小时前
c# MOdbus rto读写串口,如何不相互影响
算法·c#·多线程
代码雕刻家8 小时前
2.4.蓝桥杯-分巧克力
算法·蓝桥杯
Ulyanov8 小时前
顶层设计——单脉冲雷达仿真器的灵魂蓝图
python·算法·pyside·仿真系统·单脉冲
智者知已应修善业10 小时前
【查找字符最大下标以*符号分割以**结束】2024-12-24
c语言·c++·经验分享·笔记·算法
91刘仁德10 小时前
c++类和对象(下)
c语言·jvm·c++·经验分享·笔记·算法
diediedei10 小时前
模板编译期类型检查
开发语言·c++·算法
阿杰学AI10 小时前
AI核心知识78——大语言模型之CLM(简洁且通俗易懂版)
人工智能·算法·ai·语言模型·rag·clm·语境化语言模型
mmz120711 小时前
分治算法(c++)
c++·算法
睡一觉就好了。11 小时前
快速排序——霍尔排序,前后指针排序,非递归排序
数据结构·算法·排序算法
Tansmjs11 小时前
C++编译期数据结构
开发语言·c++·算法