carloscn / structstudy

Leetcode daily trainning by using C/C++/RUST programming.
4 stars 1 forks source link

leetcode1971: Find if Path Exists in Graph #314

Open carloscn opened 1 year ago

carloscn commented 1 year ago

Description

Can you solve this real interview question? Find if Path Exists in Graph - 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 source to vertex destination.

Given edges and the integers n, source, and destination, return true if there is a valid path from source to destination, or false otherwise.

Example 1:

image

Input: n = 3, edges = [[0,1],[1,2],[2,0]], source = 0, destination = 2 Output: true Explanation: There are two paths from vertex 0 to vertex 2:

Example 2:

image

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

Constraints:

carloscn commented 1 year ago

Analysis

并查集的基础题,关于解析请看https://github.com/youngyangyang04/leetcode-master/blob/master/problems/0684.%E5%86%97%E4%BD%99%E8%BF%9E%E6%8E%A5.md

fn init(father:&mut Vec<i32>)
{
    for i in 0..father.len() {
        father[i] = i as i32;
    }
}

fn find(father:&mut Vec<i32>, u:i32) -> i32
{
    if u != father[u as usize] {
        father[u as usize] = find(father, father[u as usize]);
        return father[u as usize];
    } else {
        return u;
    }
}

fn join(father:&mut Vec<i32>, u:i32, v:i32)
{
    let a = find(father, u);
    let b = find(father, v);
    if a == b {
        return;
    }
    father[b as usize] = a;
}

fn same(father:&mut Vec<i32>, u:i32, v:i32) -> bool
{
    let a = find(father, u);
    let b = find(father, v);
    return a == b;
}

pub fn valid_path(n: i32, edges: Vec<Vec<i32>>, source: i32, destination: i32) -> bool
{
    let mut i:usize = 0;
    let mut father:Vec<i32> = vec![0;n as usize];

    init(&mut father);

    for i in 0..edges.len() {
        join(&mut father, edges[i][0], edges[i][1]);
    }

    return same(&mut father, source, destination);
}
carloscn commented 1 year ago

Code

https://review.gerrithub.io/c/carloscn/structstudy/+/1167890 https://github.com/carloscn/structstudy/commit/1ddadd645b1cbd2adc476e96d764b3187d660ae5