27 验证给定的图是否构成有效的树(Graph Valid Tree)

文章目录

    • 1 题目
    • 2 解决方案
      • 2.1 思路
      • 2.2 时间复杂度
      • 2.4 空间复杂度
    • 3 源码

1 题目

题目:验证给定的图是否构成有效的树(Graph Valid Tree)
描述:给出 n 个节点,标号分别从 0 到 n - 1 并且给出一个无向边的列表 (给出每条边的两个顶点), 写一个函数去判断这张无向图是否是一棵树。假设列表中没有重复的边。无向边[0, 1] 和 [1, 0]是同一条边, 因此它们不会同时出现在列表中。

lintcode题号——178,难度——medium

样例1:

输入: n = 5 edges = [[0, 1], [0, 2], [0, 3], [1, 4]]
输出: true.

样例2:

输入: n = 5 edges = [[0, 1], [1, 2], [2, 3], [1, 3], [1, 4]]
输出: false.

2 解决方案

2.1 思路

  构成有效的树的充要条件是点数=边数+1图为连通图,可以使用宽度优先搜索查找所有连通的节点,对比被连通的节点数量是否与原始节点数量一致,来判断图是否为连通图

2.2 时间复杂度

  二叉树宽度优先搜索,遍历所有的节点,算法的时间复杂度为O(n)。

2.4 空间复杂度

  使用了queue队列和set集合数据结构保存节点,算法的空间复杂度为O(n)。

3 源码

细节:

  1. 有效树的充要条件:点数=边数+1,且图为连通图。
  2. BFS查找连通的节点,计算数目是否匹配。
  3. 图的邻接表的表示方式的实现。(图的另一种表示方式是邻接矩阵)

C++版本:

/**
* @param n: An integer
* @param edges: a list of undirected edges
* @return: true if it's a valid tree, or false
*/
bool validTree(int n, vector> &edges) {
    // write your code here
    if (n != edges.size() + 1)
    {
        return false;
    }

    map> graphMap = initGraph(n, edges);
    
    queue nodeQueue;
    nodeQueue.push(0);
    set nodeSet; // 使用set防止重复遍历
    nodeSet.insert(0);
    while(!nodeQueue.empty())
    {
        int cur = nodeQueue.front();
        nodeQueue.pop();
        set neighbours = graphMap.at(cur);
        for (auto it : neighbours)
        {
            if (nodeSet.find(it) != nodeSet.end())
            {
                // 跳过已经遍历过的节点
                continue;
            }
            nodeSet.insert(it);
            nodeQueue.push(it);
        }
    }

    if (nodeSet.size() != n)
    {
        return false;
    }

    return true;
}

// 图的邻接表实现
map> initGraph(int n, vector> &edges)
{
    map> result;

    // 插入key值
    for (int i = 0; i < n; i++)
    {
        result.insert({i, set()});
    }

    // 插入value值
    for (int i = 0; i < edges.size(); i++)
    {
        int u = edges.at(i).front();
        int v = edges.at(i).back();
        result.at(u).insert(v);
        result.at(v).insert(u);
    }

    return result;
}

你可能感兴趣的:(算法,#,宽度优先搜索,算法,宽度优先)