• 数组实现邻接表(java)


    受限条件下可到达节点的数目

    现有一棵由 n 个节点组成的无向树,节点编号从 0 到 n - 1 ,共有 n - 1 条边。

    给你一个二维整数数组 edges ,长度为 n - 1 ,其中 edges[i] = [ai, bi] 表示树中节点 ai 和 bi 之间存在一条边。另给你一个整数数组 restricted 表示 受限 节点。

    在不访问受限节点的前提下,返回你可以从节点 0 到达的 最多 节点数目。

    注意,节点 0 不 会标记为受限节点。

    示例 1:


    输入:n = 7, edges = [[0,1],[1,2],[3,1],[4,0],[0,5],[5,6]], restricted = [4,5]
    输出:4
    解释:上图所示正是这棵树。
    在不访问受限节点的前提下,只有节点 [0,1,2,3] 可以从节点 0 到达。

    解题思路:对于稀疏图采用邻接表来实现,这里使用数组来实现邻接表,建立三个数组,h,e,ne.

    h[i]代表点i是第几条边的起点,e[i]代表是第i条边的终点,ne[i]代表在生成第i条边前,第i条边的起点a同时还是第几条边的起点。具体代码如下

    1. public class Solution {
    2. public static void main(String args[]) {
    3. int[][] chess = {{4,1},{1,3},{1,5},{0,5},{3,6},{8,4},{5,7},{6,9},{3,2}};
    4. int[] restricted = {2,7};
    5. System.out.println(reachableNodes(10,chess,restricted));
    6. }
    7. static int[] h;
    8. static int[] e;
    9. static int[] ne;
    10. static int idx = 0;
    11. static boolean[] ban;
    12. public static int reachableNodes(int n, int[][] edges, int[] restricted) {
    13. h = new int[n];
    14. e = new int[2 * n];
    15. ne = new int[2 * n];
    16. Arrays.fill(h, -1);
    17. // 建图
    18. for (int[] e : edges) {
    19. // 无向图, 连2条边
    20. add(e[0], e[1]);
    21. add(e[1], e[0]);
    22. }
    23. ban = new boolean[n];
    24. for (int r : restricted) {
    25. ban[r] = true;
    26. }
    27. return dfs(0);
    28. }
    29. private static int dfs(int node) {
    30. if (ban[node]) {
    31. return 0;
    32. }
    33. int ans = 1;
    34. ban[node] = true;
    35. for (int i = h[node]; i != -1; i = ne[i]) {
    36. int son = e[i];
    37. ans += dfs(son);
    38. }
    39. return ans;
    40. }
    41. private static void add(int a, int b) {
    42. e[idx] = b;
    43. ne[idx] = h[a];
    44. h[a] = idx++;
    45. }
    46. }

  • 相关阅读:
    5分钟,ArcGIS 简单几步从天地图中提取出建筑物轮廓的矢量数据
    Linux Shell 自动交互功能实现
    Python 异常
    PDF怎么转换成Word?给大家分享三种简单的转换方法
    INI文件读写
    【C】字符串函数与字符函数
    TCP四次挥手
    聊聊 C++ 中的几种智能指针 (下)
    分享这几个好用的文字识别软件,教你快速识别
    图片怎么转文字?建议收藏这些方法
  • 原文地址:https://blog.csdn.net/perception952/article/details/126369873