代码随想录–图论部分
day 50 图论第一天
图论基础概念
代码随想录知识链接:代码随想录
对度、节点、有向图无向图先有个概念,并且了解图要怎么存在电脑里
深度优先搜索
代码随想录知识链接:代码随想录
广度优先搜索
代码随想录知识链接:代码随想录
这两个搜索方式要理解是怎么实现的,之后就可做题了
一、卡码网98–所有可达路径
代码随想录题目链接:代码随想录
给定一个有 n 个节点的有向无环图,节点编号从 1 到 n。请编写一个函数,找出并返回所有从节点 1 到节点 n 的路径。每条路径应以节点编号的列表形式表示。
ACM模式需要考虑图的存储方式(符合笔试风格),可以使用邻接矩阵也可以使用邻接表
邻接矩阵是用二维数组来表示图结构,graph[i][j]
为1说明节点i与j之间有路径,否则无
记录下来后做个正常的深度优先搜索即可
代码如下:
# include <iostream>
# include <vector>
using namespace std;
vector<int> path;
vector<vector<int>> result;
void dfs(const vector<vector<int>> & graph, int x, int n)
{
if(x == n)
{
result.push_back(path);
return;
}
for (int i = 1; i <= n; i++)
{
if (graph[x][i] == 1)
{
path.push_back(i);
dfs(graph, i, n);
path.pop_back();
}
}
}
int main()
{
int N, M;
while(cin >> N >> M)
{
vector<vector<int>> graph(N + 1, vector<int>(N + 1, 0));
while(M --)
{
int s, t;
cin >> s >> t;
graph[s][t] = 1;
}
path.push_back(1);
dfs(graph, 1, N);
if (result.size() == 0) cout << -1 << endl;
for (const vector<int> &pa : result)
{
for (int i = 0; i < pa.size() - 1; i++)
{
cout << pa[i] << " ";
}
cout << pa[pa.size() - 1] << endl;
}
}
return 0;
}
二、力扣797–所有可能的路径
代码随想录题目链接:代码随想录
给你一个有 n 个节点的 有向无环图(DAG),请你找出所有从节点 0 到节点 n-1 的路径并输出(不要求按特定顺序)
和上题一模一样,只是省去了储存图的方式
代码如下:
class Solution {
public:
vector<vector<int>> result;
vector<int> path;
void dfs(const vector<vector<int>> graph, int x, int n)
{
if(x == n-1)
{
result.push_back(path);
return;
}
for(int i = 0; i < n; i ++)
{
if(graph[x][i] == 1)
{
path.push_back(i);
dfs(graph, i, n);
path.pop_back();
}
}
}
vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) {
vector<vector<int>> graph_true(graph.size(), vector<int>(graph.size(), 0));
for(int i = 0; i < graph.size(); i ++)
for(int j = 0; j < graph[i].size(); j ++)
graph_true[i][graph[i][j]] = 1;
path.push_back(0);
dfs(graph_true, 0, graph.size());
return result;
}
};