当前位置:网站首页>婴儿名字[连通分量之邻接矩阵与DFS]
婴儿名字[连通分量之邻接矩阵与DFS]
2022-06-21 18:01:00 【REN_林森】
邻接矩阵与DFS
前言
图的基本功之一,给定节点和边(节点对),统计连通分量的个数,当然也可以以其他形式给出,例如婴儿名字。通过其可练习常见图物理结构实现–邻接矩阵。
一、婴儿名字

二、邻接矩阵与DFS
package everyday;
import java.util.*;
// 婴儿名字
public class TrulyMostPopular {
/* target:有类似名字的频数加起来,取一个在字典上最小的名字作为代表。 如何处理类似名字?可用邻接表处理好,然后遍历每个连通分量。 */
Map<String, Set<String>> graph = new HashMap<>();
public String[] trulyMostPopular(String[] names, String[] synonyms) {
// 根据synonyms来建图
buildGraph(synonyms);
// 记录每个单词的频数。
Map<String, Integer> val = new HashMap<>();
for (String name : names) {
int idx = getRealNameIdx(name);
String key = name.substring(0, idx);
int value = Integer.parseInt(name.substring(idx + 1, name.length() - 1));
val.put(key, value);
// bug1:graph中没有这些孤立的点
addNode(key);
}
// 遍历所有连通分量
List<String> ans = new ArrayList<>();
for (String name : names) {
name = name.substring(0, getRealNameIdx(name));
if (graph.containsKey(name)) {
min = (char) ('z' + 1) + "";
int total = dfs(name, val);
ans.add(min + '(' + total + ')');
}
}
return ans.toArray(new String[0]);
}
String min;
private int dfs(String name, Map<String, Integer> val) {
// 获取最小名字
if (val.containsKey(name) && min.compareTo(name) > 0) min = name;
// 结果为自身,再加所有相邻节点。
int rs = val.getOrDefault(name, 0);
// 得到所有next节点
Set<String> next = graph.get(name);
// 走过的节点就不要。
graph.remove(name);
if (null == next) return rs;
for (String s : next) {
// 只算未计算的节点值。
if (graph.containsKey(s))
rs += dfs(s, val);
}
return rs;
}
private int getRealNameIdx(String name) {
int n = name.length();
for (int i = name.length() - 1; i >= 0; i--) {
if (Character.isLetter(name.charAt(i))) break;
--n;
}
return n;
}
private void buildGraph(String[] synonyms) {
for (String synonym : synonyms) {
String[] strs = synonym.split(",");
addEdge(strs[0].substring(1), strs[1].substring(0, strs[1].length() - 1));
}
}
private void addEdge(String node, String another) {
// 添加节点
addNode(node);
addNode(another);
// 设置边
graph.get(node).add(another);
graph.get(another).add(node);
}
private void addNode(String node) {
if (!graph.containsKey(node)) graph.put(node, new HashSet<>());
}
}
总结
1)求连通分量变体。
2)邻接矩阵具体实现方式。
注:连通分量和并查集(初始化/合并/查找根节点)精密联系,可采用并查集解。
参考文献
[1] LeetCode 婴儿名字
边栏推荐
- The R language catiols package divides the data, randomforest package constructs the random forest model, uses the importance function to calculate the importance of each feature in the random forest
- 老师们,oracle-cdc遇到不能解析的dml语句,因为这个语句里面有个字段是比较特殊的空间地理位
- 华为鸿蒙认证测试题,你能答对几道?
- [high frequency interview questions] difficulty 1.5/5, classic "prefix and + two points" application questions
- [pwn基础]Pwntools学习
- 從“村辦企業”到“百億集團”,紅星實業何以完成“蝶變”?
- What is the process of futures account opening? Is it safe to open an account online
- SQL操作:WITH表达式及其应用
- 根据数据中的key获取value值
- WWDC22 多媒体特性汇总
猜你喜欢

Use the uniapp framework to build the zheliban micro application (single sign on, embedded point, aging adaptation, RPC gateway)

11 introduction and installation of beautiful soup parsing library

vivo 容器集群监控系统架构与实践

鸿蒙之后,华为宣布再将捐赠欧拉,鸿蒙和欧拉的捐赠预计将给业界带来哪些影响?

MySQL的MVCC实现原理

Delete the specified screen

How many correct answers can you get to Huawei Hongmeng certification test questions?

11 Beautiful Soup 解析庫的簡介及安裝

【一起上水硕系列】Day One

Second cloud's original fully compatible solution for Xinchuang is upgraded to help accelerate the implementation of Xinchuang industry
随机推荐
GetEmptyBlcoksPre Info
The R language uses the follow up The plot function visualizes the longitudinal follow-up chart of multiple ID (case) monitoring indicators, and uses line Col parameter custom curve color (color)
线上开期货户是否安全啊?不去线下可以开户吗?
36氪首发 | 聚焦健康险产品创新,「英仕健康」已获4轮融资
36 krypton launched | focusing on the innovation of health insurance products, and "Yingshi health" has obtained four rounds of financing
ThreadLocal与线程池在使用中可能会出现的两个问题
文献分析 Citespace 6.1.2 下载及安装教程
R语言glm函数构建二分类logistic回归模型(family参数为binomial)、使用coef函数获取模型系数并解析系数意义
华为又发新品?这几款功能太优秀了
2022年6月25日PMP考试通关宝典-4
MySQL的MVCC实现原理
Hongmeng version of "Tiktok" is a great experience
Nepal graph has settled in Alibaba cloud computing nest to help enterprises build a super large-scale map database on the cloud
如何使用DevExpress WPF在WinUI中创建第一个MVVM应用?
MFC界面库BCGControlBar v33.0 - 桌面警报窗口、网格控件升级
linux-mysql-命令
技术分享 | MySQL:caching_sha2_password 快速问答
Delete the specified screen
医疗费用清单秒速录入,OCR识别助力效率倍增
Niuke: merging two ordered arrays