第六十四天打卡 | 卡码网98 所有可达路径(深搜 邻接矩阵版)

卡码网98 所有可达路径


深搜+邻接矩阵写法

#include <iostream>
#include <vector>
#include <string>
using namespace std;


vector<string> ans;
string path = "1";

void dfs(vector<vector<int>>& grid, int index, int n) {
    if (index == n) {
        ans.push_back(path);
        return;
    }
    for (int i = 1; i <= n; i++) {
        if (grid[index][i] == 1) {
            string temp = path;
            path += " ";
            path += to_string(i);
            dfs(grid, i, n);
            path = temp;
        }
    }
} 

int main() {
    int n, m;
    cin >> n >>  m;
    vector<vector<int>> grid(n+1, vector<int>(n+1,0));
    while (m--) {
        int a, b;
        cin >> a >> b;
        grid[a][b] = 1;
    }
    dfs(grid, 1, n);
    if (ans.size() == 0) {
        cout << -1 << endl;
        return 0;
    }
    for (int i = 0; i < ans.size(); i++) {
        cout << ans[i] << endl;
    }
}

深搜+邻接表写法

#include <iostream>
#include <list>
#include <vector>
#include <string>
using namespace std;

vector<string> ans;
string path = "1";

void dfs(vector<list<int>>& l, int index, int n) {
    if (index == n-1) {
        ans.push_back(path);
        return;
    }
    for (int i : l[index]) {
        string temp = path;
        path += " ";
        path += to_string(i+1);
        dfs(l, i, n);
        path = temp;
    }
} 

int main() {
    int n, m;
    cin >> n >> m;
    vector<list<int>> l(n);
    int s, t;
    for (int i = 0; i < m; i++) {
        cin >> s >> t;
        l[s-1].push_back(t-1);
    }
    dfs(l, 0, n);
    if (ans.size() == 0) {
        cout << -1 << endl;
        return 0;
    }
    for (int i = 0; i < ans.size(); i++) {
        cout << ans[i] << endl;
    }
}

这题用广搜会比较麻烦一点,要记录路径,在深搜中我们可以用递归逻辑来实现,广搜就是迭代法,我们不能再只用一个变量path记录所有的路径再存入,而是要一次性用vector数组记录对应的路径,并且要再过程中新增路径条数。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值