leetcode323. Number of Connected Components in an Undirected Graph

本文介绍两种高效算法来寻找无向图中的所有连通分量:一种使用广度优先搜索(BFS),另一种采用并查集(Union Find)。通过这两种方法可以将图中的节点按其所属的连通分量进行分组。

解法一

bfs

/**
 * @Author taotao
 * @Date 9/8/17
 */

class UndirectedGraphNode {
    int label;
    ArrayList<UndirectedGraphNode> neighbors;
    UndirectedGraphNode(int x) {
        label = x;
        neighbors = new ArrayList<UndirectedGraphNode>();
    }
};

public class FindTheConnectedComponentInTheUndirectedGraph_lint_3 {
    public List<List<Integer>> connectedSet(ArrayList<UndirectedGraphNode> nodes) {
        Map<UndirectedGraphNode, Boolean> visited = new HashMap<>();
        for (UndirectedGraphNode node : nodes) {
            visited.put(node, false);
        }
        List<List<Integer>> result = new ArrayList<>();
        for (UndirectedGraphNode node : nodes) {
            if (visited.get(node) == false) {
                bfs(node, visited, result);
            }
        }

        return result;
    }
    public void bfs(UndirectedGraphNode node, Map<UndirectedGraphNode, Boolean> visited,
                    List<List<Integer>> result) {
        List<Integer> row = new ArrayList<>();
        Queue<UndirectedGraphNode> queue = new LinkedList<>();
        visited.put(node, true);
        queue.offer(node);
        while (!queue.isEmpty()) {
            UndirectedGraphNode u = queue.poll();
            row.add(u.label);
            for (UndirectedGraphNode v : u.neighbors) {
                if (visited.get(v) == false) {
                    visited.put(v, true);
                    queue.offer(v);
                    row.add(v.label);
                }
            }
        }

        Collections.sort(row);
        result.add(row);
    }
    public static void main(String[] args) {
        FindTheConnectedComponentInTheUndirectedGraph_lint_3 model = new FindTheConnectedComponentInTheUndirectedGraph_lint_3();
        UndirectedGraphNode a = new UndirectedGraphNode(1);
        UndirectedGraphNode b = new UndirectedGraphNode(2);
        ArrayList<UndirectedGraphNode> list = new ArrayList<>();
        list.add(a);
        list.add(b);
        List<List<Integer>> l = model.connectedSet(list);
        System.out.print(l);
    }
}

解法二

UnionFind

/**
 * @Author RenXintao
 * @Date 9/8/17
 * @method: UnionFind
 */
class UnionFind {
    HashMap<Integer, Integer> father = new HashMap<>();
    UnionFind(HashSet<Integer> hashSet) {
        for (Integer now : hashSet) {
            father.put(now, now);
        }
    }
    int find(int x) {
        int parent = father.get(x);
        while (parent != father.get(parent)) {
            parent = father.get(parent);
        }

        return parent;
    }
    int compressed_find(int x) {
        int parent = father.get(x);
        while (parent != father.get(parent)) {
            parent = father.get(parent);
        }

        int next;
        while (x != father.get(x)) {
            next = father.get(x);
            father.put(x, parent);
            x = next;
        }

        return parent;
    }
    void union(int x, int y) {
        int fa_x = father.get(x);
        int fa_y = father.get(y);
        if (fa_x != fa_y) {
            father.put(fa_x, fa_y);
        }
    }

}
public class FindTheConnectedComponentInTheUndirectedGraph_lint_3_1 {
    List<List<Integer>> print(HashSet<Integer> hashSet, UnionFind uf, int n) {
        List<List<Integer>> ans = new ArrayList<List<Integer>>();
        HashMap<Integer, List<Integer>> hashMap = new HashMap<Integer, List<Integer>>();
        for (int i : hashSet) {
            int fa = uf.find(i);
            if (!hashMap.containsKey(fa)) {
                hashMap.put(fa, new ArrayList<Integer>());
            }
            List<Integer> now = hashMap.get(fa);
            now.add(i);
            hashMap.put(fa, now);
        }

        for (List<Integer> now : hashMap.values()) {
            Collections.sort(now);
            ans.add(now);
        }

        return ans;
    }
    public List<List<Integer>> connnectedSet(ArrayList<UndirectedGraphNode> nodes) {
        HashSet<Integer> hashSet = new HashSet<>();
        for (UndirectedGraphNode now : nodes) {
            hashSet.add(now.label);
            for (UndirectedGraphNode neighbour : now.neighbors) {
                hashSet.add(neighbour.label);
            }
        }

        UnionFind uf = new UnionFind(hashSet);

        for (UndirectedGraphNode now : nodes) {
            for (UndirectedGraphNode neighbour : now.neighbors) {
                int fnow = uf.find(now.label);
                int fneighbour = uf.find(neighbour.label);
                if (fnow != fneighbour) {
                    uf.union(now.label, neighbour.label);
                }
            }
        }

        return print(hashSet, uf, nodes.size());
    }
}
### 关于VSCode中LeetCode插件命令未找到的解决方案 在使用VSCode安装LeetCode插件后,如果遇到`'leetcode.signin'`命令未找到的问题,通常可能是由于以下原因导致:插件未正确安装、插件依赖项缺失或配置文件存在问题[^1]。以下是详细的解决方法: #### 1. 检查插件是否正确安装 确保已从官方市场安装了正确的LeetCode插件。可以通过以下步骤确认: - 打开VSCode的扩展市场(快捷键 `Ctrl+Shift+X`)。 - 搜索“LeetCode”并选择评价较高且下载量较大的插件进行安装。 若插件安装失败或不完整,可以尝试卸载后重新安装[^2]。 #### 2. 更新Node.js环境 LeetCode插件依赖Node.js运行时环境。如果Node.js版本过低或未安装,可能会导致插件功能异常。建议检查Node.js版本,并确保其为最新稳定版本: ```bash node -v ``` 如果版本低于14.x,请访问[Node.js官网](https://nodejs.org/)下载并安装最新版本[^3]。 #### 3. 检查插件依赖项 某些LeetCode插件需要额外的依赖项才能正常工作。例如,可能需要全局安装`leetcode-cli`工具: ```bash npm install -g leetcode-cli ``` 安装完成后,重启VSCode以确保所有依赖项加载成功[^4]。 #### 4. 配置插件设置 部分LeetCode插件需要手动配置才能正常使用。可以在VSCode的`settings.json`文件中添加以下内容: ```json { "leetcode.enabled": true, "leetcode.defaultLanguage": "python", "leetcode.problemsDirectory": "./problems" } ``` 根据实际需求调整配置项[^5]。 #### 5. 检查命令面板 确保通过命令面板调用`leetcode.signin`命令时,命令名称完全匹配。可以通过以下方式打开命令面板并搜索相关命令: - 快捷键 `Ctrl+Shift+P`。 - 输入`leetcode`并查看可用命令列表。 如果命令仍然不可见,可能需要重启VSCode或重新安装插件[^6]。 #### 6. 查看插件日志 大多数VSCode插件会在输出窗口记录日志信息。可以通过以下步骤查看LeetCode插件的日志: - 打开“输出”面板(快捷键 `Ctrl+Shift+U`)。 - 选择“LeetCode”作为日志源。 - 检查是否有错误提示并根据提示解决问题[^7]。 ### 示例代码 以下是一个简单的Python脚本示例,用于验证LeetCode插件的功能是否正常: ```python # 测试LeetCode插件是否正常工作 def test_leetcode_plugin(): print("LeetCode插件测试成功!") test_leetcode_plugin() ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值