Connecting Graph
2024-08-27 03:05:45
Given n
nodes in a graph labeled from 1
to n
. There is no edges in the graph at beginning.
You need to support the following method:
1. connect(a, b)
, add an edge to connect node a
and node b. 2.
query(a, b)`, check if two nodes are connected
Example
5 // n = 5
query(1, 2) return false
connect(1, 2)
query(1, 3) return false
connect(2, 4)
query(1, 4) return true
思路:考察图。定义root节点,从root节点入手,判断root节点是否相同,相同即存在连接关系。
public class ConnectingGraph {
private int[] father = null;
public ConnectingGraph(int n) {
// initialize your data structure here.
father = new int[n + 1];
for (int i = 1; i <= n; i++) {
father[i] = i;
}
} public void connect(int a, int b) {
// Write your code here
int rootA = find(a);
int rootB = find(b);
if (rootA != rootB) {
father[rootA] = rootB;
}
} public boolean query(int a, int b) {
// Write your code here
int rootA = find(a);
int rootB = find(b);
return rootA == rootB; } private int find(int x) {
if (father[x] == x) {
return x;
}
return find(father[x]);
}
}
最新文章
- MySQL 表分区 报错:Table has no partition for value XXX
- Oracle导出表(即DMP文件)的两种方法
- oracle本机登录不上dba的权限不足错误
- java中判断一个字符串是否“都为数字”和“是否包含数字”和“截取数字”
- Ios开发之定位CLLocationManager
- jquery 动态事件绑定(0512)
- A Tour of Go Exercise: Images
- 关于TFS2012无法发送警报邮件的问题
- 【转】如何测试CTS4.0 -- 不错
- hadoop入门级总结三:hive
- 【Android 系统开发】下载 编译 Android源代码 和 Android kernel源代码
- .Net Core3 新特性/新功能 16条
- Linux课题实践四——ELF文件格式分析
- 维护贴--linux下 mysql数据库的备份和还原 (转)
- 865. Smallest Subtree with all the Deepest Nodes 有最深节点的最小子树
- 一个浏览器Fuzzing框架的学习
- javaweb中如何给自己的网站更改ico图标
- GITHUB随笔 15-5月 junit
- 后台开发面试题(.net与java)
- 安装CentOS 7 文字版
热门文章
- Asp.Net Core 调用第三方Open API查询物流数据
- SSRS Reporting Service安装与部署
- BJFU——205基于顺序存储结构的图书信息表的排序
- English Grammar in Use - Part1 Present and past
- WUSTOJ 1327: Lucky Numbers(Java)
- go 错误
- 题解-AtCoder ARC-083F Collecting Balls
- jquery easyui form表单一开始就自动启用验证了,修改为form提交的时候在开启验证
- python实现ssh及sftp功能
- android 动画总结一