算法训练营|图论第一天 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;
}
相关推荐
Zzz不能停1 分钟前
堆排序算法及大小堆区别
数据结构·算法
zd84510150011 分钟前
stm32f407 电机多轴联动算法
stm32·单片机·算法
代码游侠14 分钟前
应用——Linux FrameBuffer图形显示与多线程消息系统项目
linux·运维·服务器·开发语言·前端·算法
Eloudy14 分钟前
矩阵张量积(Kronecker积)的代数性质与定理
算法·量子计算
多米Domi01125 分钟前
0x3f 第25天 黑马web (145-167)hot100链表
数据结构·python·算法·leetcode·链表
LYFlied25 分钟前
【每日算法】LeetCode 207. 课程表
算法·leetcode·职场和发展
sali-tec27 分钟前
C# 基于OpenCv的视觉工作流-章7-膨胀
图像处理·人工智能·opencv·算法·计算机视觉
叫我:松哥30 分钟前
基于机器学习的地震风险评估与可视化系统,采用Flask后端与Bootstrap前端,系统集成DBSCAN空间聚类算法与随机森林算法
前端·算法·机器学习·flask·bootstrap·echarts·聚类
一起养小猫31 分钟前
LeetCode100天Day12-删除重复项与删除重复项II
java·数据结构·算法·leetcode
小O的算法实验室37 分钟前
2023年IEEE TITS SCI2区TOP,增强遗传算法+分布式随机多无人机协同区域搜索路径规划,深度解析+性能实测
算法·论文复现·智能算法·智能算法改进