《中英双解》leetCode Find if path exists in graph

该博客介绍了如何使用广度优先搜索(BFS)和深度优先搜索(DFS)在有向图中查找从指定起始顶点到目标顶点的有效路径。通过建立邻接表并遍历图的节点来判断是否存在路径。示例展示了在不同图结构下,这两种方法的正确性和效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

There is a bi-directional graph with n vertices, where each vertex is labeled from 0 to n - 1 (inclusive). The edges in the graph are represented as a 2D integer array edges, where each edges[i] = [ui, vi] denotes a bi-directional edge between vertex ui and vertex vi. Every vertex pair is connected by at most one edge, and no vertex has an edge to itself.

You want to determine if there is a valid path that exists from vertex start to vertex end.

Given edges and the integers nstart, and end, return true if there is a valid path from start to end, or false otherwise.

有一个具有 n个顶点的 双向 图,其中每个顶点标记从 0 到 n - 1(包含 0 和 n - 1)。图中的边用一个二维整数数组 edges 表示,其中 edges[i] = [ui, vi] 表示顶点 ui 和顶点 vi 之间的双向边。 每个顶点对由 最多一条 边连接,并且没有顶点存在与自身相连的边。

请你确定是否存在从顶点 start 开始,到顶点 end 结束的 有效路径 。

给你数组 edges 和整数 n、start和end,如果从 start 到 end 存在 有效路径 ,则返回 true,否则返回 false 。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-if-path-exists-in-graph
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

Example 1:

Input: n = 3, edges = [[0,1],[1,2],[2,0]], start = 0, end = 2
Output: true
Explanation: There are two paths from vertex 0 to vertex 2:
- 0 → 1 → 2
- 0 → 2

Example 2:

Input: n = 6, edges = [[0,1],[0,2],[3,5],[5,4],[4,3]], start = 0, end = 5
Output: false
Explanation: There is no path from vertex 0 to vertex 5.

Constraints:

  • 1 <= n <= 2 * 105
  • 0 <= edges.length <= 2 * 105
  • edges[i].length == 2
  • 0 <= ui, vi <= n - 1
  • ui != vi
  • 0 <= start, end <= n - 1
  • There are no duplicate edges.
  • There are no self edges.

BFS

class Solution {
    public boolean validPath(int n, int[][] edges, int start, int end) {
        HashMap<Integer, List<Integer>> graph = new HashMap<Integer,List<Integer>>();
        for (int i= 0;i <edges.length;i++)
        {
            if(graph.containsKey(edges[i][0]))
            {
                graph.get(edges[i][0]).add(edges[i][1]);
            }
            else
            {
                List<Integer> temp = new ArrayList<Integer>();
                temp.add(edges[i][1]);
                graph.put(edges[i][0],temp);
            }
            if(graph.containsKey(edges[i][1]))
            {
                graph.get(edges[i][1]).add(edges[i][0]);
            }
            else
            {
                List<Integer> temp2 = new ArrayList<Integer>();
                temp2.add(edges[i][0]);
                graph.put(edges[i][1],temp2);
            }
        }
        int[] visited = new int[n];
        Queue<Integer> queue = new LinkedList<Integer>();
        queue.add(start);
        visited[start] = 1;
        while(!queue.isEmpty())
        {
            int top = queue.remove();
            if(graph.containsKey(top))
            {
                for(int k=0;k < graph.get(top).size();k++)
                {
                    if(visited[graph.get(top).get(k)] != 1)
                    {
                        queue.add(graph.get(top).get(k));
                        visited[graph.get(top).get(k)] = 1;
                    }
                }
            }
        }
        return visited[end] == 1;
        
    }
}

 DFS

class Solution {
    public boolean validPath(int n, int[][] edges, int start, int end) {
       boolean[] visited = new boolean[n + 1];
       boolean newVisited = true;
       visited[start] = true;

       while(!visited[end] && newVisited){
           newVisited = false;
           for(int[] edge : edges){
              if(visited[edge[0]] && !visited[edge[1]]){
                  visited[edge[1]] = true;
                  newVisited = true;
              }
              if(!visited[edge[0]] && visited[edge[1]]){
                  visited[edge[0]] = true;
                  newVisited = true;
              }
           }
       }
       return visited[end];
   }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值