中级农民
- 积分
- 104
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2021-7-7
- 最后登录
- 1970-1-1
|
本帖最后由 je4ever 于 2024-2-16 07:33 编辑
会有。
这道题我目前的解法就是用union set find算法,如果一个union set里有loop,那这个union set里就不会有unreachable node,因为就像公路如果有一个环连接所有公路,那每个node都是可以到达的。
贴上我的代码仅供参考。- public int countMinimunUnreachableWarehouses(int warehouseNodes, int[][] edges) {
- int[] parent = new int[warehouseNodes + 1];
- Arrays.fill(parent, -1);
- Set<Integer> cycleSet = new HashSet<>();
- for(int i = 0; i < edges.length; i++) {
- int f = edges[i][0];
- int t = edges[i][1];
- int fset = find(parent, f);
- int tset = find(parent, t);
- if(fset == tset)
- cycleSet.add(fset);
- else
- parent[fset] = tset;
- }
- int count = 0;
- Set<Integer> visited = new HashSet<>();
- for(int i = 1; i < warehouseNodes + 1; i++) {
- int root = find(parent, i);
- if(visited.contains(root))
- continue;
- else {
- visited.add(root);
- if(!cycleSet.contains(root))
- count++;
- }
- }
- return count;
- }
- private int find(int[] parent, int n) {
- if(parent[n] == -1)
- return n;
- return find(parent, parent[n]);
- }
复制代码 |
|