首页 > 其他分享 >寻找是否存在从source到destination的路径

寻找是否存在从source到destination的路径

时间:2024-04-21 18:22:45浏览次数:19  
标签:路径 int graph destination source visited 节点

The Find if Path Exists in Graph problem involves determining whether there is a path between two given nodes (source and destination) in an undirected graph. The graph is represented by n nodes and a list of edges, where each edge specifies a connection between two nodes.

Given:

n: Number of nodes in the graph.
edges: List of edges where each edge is represented as [u, v], indicating an undirected edge between node u and node v.
source: The starting node for the path.
destination: The target node to reach.

Objective:
You need to implement a solution that can determine if there exists a path from the source node to the destination node in the given graph.

Output:
Return True if there exists a path from source to destination, otherwise return False.

解题:

  1. 重构给出的图结构
    题目给出的是一对对二维数组(向量表)edges,用来表示图中所有的边。
    重构:从已有的二维数组中构建一个邻接表,这会让之后遍历每一个节点和它的相邻节点变得高效。

  2. DFS函数的逻辑:
    1.)我们需要一个集合visited来存储每次循环访问过的节点,每次只要是访问过的节点,都把它放到visite集合中。
    2.) 构建一个递归函数,从source节点开始,首先判断这个source是不是就是要找的destination,如果是则返回true,否则找到和source相连接的所有邻节点,选择其中一个并判断:这个节点有没有被遍历过(是否在visited中能找到),如果没有,则选中它作为递归的起点,把它作为新的source递归调用这个函数,重复以上的操作。
    3.)通过递归可以充分遍历完图中的所有节点,如果最终没有找到预先给定的destination,则表示不存在从source到destination的路径,返回false。

  class Solution {
public:
    bool validPath(int n, vector<vector<int>>& edges, int source, int destination) {
        unordered_map<int, vector<int>> graph;

        for (const auto &edge: edges) {
            int u = edge[0];
            int v = edge[1];

            graph[u].push_back(v);
            graph[v].push_back(u);
        }

        unordered_set<int> visited;
        return dfs(source, destination, graph, visited);
    }


    bool dfs(int node, int destination, unordered_map<int, vector<int>> &graph, unordered_set<int> &visited) {
        if (node == destination) {
            return true;
        }

        visited.insert(node);
        for (int neighbor: graph[node]) {
            if (visited.find(neighbor) == visited.end()) {
                if (dfs(neighbor, destination, graph, visited)) {
                    return true;
                }
            }
        }
        return false;
    }
};
  1. 首先也是和方法一一样重构图结构。
  2. BFS函数逻辑:
    1.)同样需要建立一个集合visited用来存储访问过的节点,以保证遍历的过程中循环的有界性以及避免重复访问同一个节点。
    2.)这次用一个while循环替代递归,对于while,需要创造一个结束的边界条件:使用queue容器并判断queue容器是否为空,为空则停止循环。具体操作:把关注的那个节点(没有被访问过的)放入队列queue中,进入循环while判断,把这个节点pop出去,并把这个节点存储到visted集合内。找到和当前节点相邻的同时未被访问过的一个新节点,把它作为新关注的节点并放到队列中,进入下一轮while循环,确定这个节点是否等于destination,如果等于则结束循环,否则找一个与该节点相邻的下一个邻接点重复循环,如果最后queue在进行while判断时为空,那么循环终止,表示遍历完所有节点,没有找到从source到destination的路径。
class Solution {
public:
    bool validPath(int n, vector<vector<int>>& edges, int source, int destination) {
       unordered_map<int, vector<int>> graph;

       for (const auto &edge: edges) {
        int u = edge[0];
        int v = edge[1];
        graph[u].push_back(v);
        graph[v].push_back(u);
       }

       queue<int> queue;
       unordered_set<int> visited;

       queue.push(source);
       visited.insert(source);

       while (!queue.empty()) {
        int node = queue.front();
        queue.pop();

        if (node == destination) {
            return true;
        }

        for (int neighbor: graph[node]) {
            if (visited.find(neighbor) == visited.end()) {
                visited.insert(neighbor);
                queue.push(neighbor);
            }
        }

       }
       return false;
    }
};

标签:路径,int,graph,destination,source,visited,节点
From: https://www.cnblogs.com/songyaxuan/p/18149280

相关文章

  • [leetcode 周赛] 100276. 最短路径中的边
    solution使用dijkstra算法求出顶点0到每个顶点的最小距离dp[i]然后再从n-1开始遍历,如果dp[to]+w==dp[from],这条边符合条件importjava.util.*;classSolution{publicstaticvoidmain(String[]args){Solutionsolution=newSolution();......
  • 贡献法之求树上上任意两点间的路径之和
    一图胜千言开始造火箭虽然我们可以求出,总共的dis(i,j),但分散到每一个小dis(i,j),由于存在向上取整操作,我们需要求出将每一个小dis(i,j)给补成k的倍数的补数之和!此处我们采用树形dp。dp[u][j]表示以u的子节点到根节点root的距离对k取余的值为j的点的个数我们如何求树上任意两......
  • 更改ollama模型存储路径
    默认情况下,ollama模型的存储目录如下:macOS:~/.ollama/modelsLinux:/usr/share/ollama/.ollama/modelsWindows:C:\Users\<username>\.ollama\models如果需要使用不同的目录,则需设置环境变量OLLAMA_MODELS,把它设置为所选目录。https://github.com/ollama/ollama/blob/ma......
  • Bingbong的回文路径
    Bingbong的回文路径题目描述Bingbong有一棵有根树,根节点为$1$,总共有$n$个节点。树中的节点通过$n−1$条无向边相连,每条边的权重为$1$。树中的每个节点包含一个小写字母。Bingbong将选择从节点$u$开始,并在选择最短路径的情况下到达节点$v$。他想知道他所走路径形成的......
  • com.alibaba.druid.pool.DataSourceClosedException: dataSource already closed at S
     适用的druid数据库连接池一直有问题,无法连接,但是什么都没改过。排查了数据库(数据库单独连接没问题)、防火墙、IP白名单等步骤后,重启服务器、重启应用后都无法解决。重启应用过程中发现了应用无法正常启动的情况,这点让人觉得很意外,于是想看下现在服务器上运行的jar包情况,命令是......
  • web server apache tomcat11-08-JNDI Resources
    前言整理这个官方翻译的系列,原因是网上大部分的tomcat版本比较旧,此版本为v11最新的版本。开源项目从零手写实现tomcatminicat别称【嗅虎】心有猛虎,轻嗅蔷薇。系列文章webserverapachetomcat11-01-官方文档入门介绍webserverapachetomcat11-02-setup启动web......
  • blog.admin net8发布二级目录,及图片上传路径处理
    1、发布二级目录,修改以下配置,及对应的二级目录名跟配置的一致 2、图片上传a、修改后台api代码imgController.cspublicasyncTask<MessageModel<string>>InsertPicture([FromForm]UploadFileDtodto){if(dto.file==null||!dto.file.Any())returnFail......
  • NL2SQL技术方案系列(1):NL2API、NL2SQL技术路径选择;LLM选型与Prompt工程技巧,揭秘项目落
    NL2SQL技术方案系列(1):NL2API、NL2SQL技术路径选择;LLM选型与Prompt工程技巧,揭秘项目落地优化之道NL2SQL基础系列(1):业界顶尖排行榜、权威测评数据集及LLM大模型(SpidervsBIRD)全面对比优劣分析[Text2SQL、Text2DSL]NL2SQL基础系列(2):主流大模型与微调方法精选集,Text2SQL经典算法......
  • 小心启动路径带来的小坑
    最近在做一个需求,需要调用同级目录的第三方程序进行数据处理。快速的薅了一个实现Processprocess=newProcess();process.StartInfo=newProcessStartInfo(){};process.StartInfo.FileName="ProgramName.exe";process.StartInfo.CreateNoWindow=true;process.Star......
  • 用log4net写入不同路径的日志文件
      用log4net写入不同路径的日志文件///<summary>///根据_jobName路径写入不同日志///</summary>publicclassNLogger{privatestaticDictionary<string,ILog>Loggers=newDictionary<string,ILog>();privatestr......