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]);
}
}

最新文章

  1. MySQL 表分区 报错:Table has no partition for value XXX
  2. Oracle导出表(即DMP文件)的两种方法
  3. oracle本机登录不上dba的权限不足错误
  4. java中判断一个字符串是否“都为数字”和“是否包含数字”和“截取数字”
  5. Ios开发之定位CLLocationManager
  6. jquery 动态事件绑定(0512)
  7. A Tour of Go Exercise: Images
  8. 关于TFS2012无法发送警报邮件的问题
  9. 【转】如何测试CTS4.0 -- 不错
  10. hadoop入门级总结三:hive
  11. 【Android 系统开发】下载 编译 Android源代码 和 Android kernel源代码
  12. .Net Core3 新特性/新功能 16条
  13. Linux课题实践四——ELF文件格式分析
  14. 维护贴--linux下 mysql数据库的备份和还原 (转)
  15. 865. Smallest Subtree with all the Deepest Nodes 有最深节点的最小子树
  16. 一个浏览器Fuzzing框架的学习
  17. javaweb中如何给自己的网站更改ico图标
  18. GITHUB随笔 15-5月 junit
  19. 后台开发面试题(.net与java)
  20. 安装CentOS 7 文字版

热门文章

  1. Asp.Net Core 调用第三方Open API查询物流数据
  2. SSRS Reporting Service安装与部署
  3. BJFU——205基于顺序存储结构的图书信息表的排序
  4. English Grammar in Use - Part1 Present and past
  5. WUSTOJ 1327: Lucky Numbers(Java)
  6. go 错误
  7. 题解-AtCoder ARC-083F Collecting Balls
  8. jquery easyui form表单一开始就自动启用验证了,修改为form提交的时候在开启验证
  9. python实现ssh及sftp功能
  10. android 动画总结一