当前位置:网站首页>Infant name [adjacency matrix and DFS of connected components]
Infant name [adjacency matrix and DFS of connected components]
2022-06-22 00:04:00 【REN_ Linsen】
Adjacency matrix and DFS
Preface
One of the basic skills of graph , Given nodes and edges ( Node pair ), Count the number of connected components , Of course, it can also be given in other forms , For example, the baby's name . It can be used to practice the physical structure of common graphs – Adjacency matrix .
One 、 Baby's name

Two 、 Adjacency matrix and DFS
package everyday;
import java.util.*;
// Baby's name
public class TrulyMostPopular {
/* target: The frequencies with similar names add up , Take the smallest name in the dictionary as a representative . How to deal with similar names ? The adjacency table can be used to handle , Then traverse each connected component . */
Map<String, Set<String>> graph = new HashMap<>();
public String[] trulyMostPopular(String[] names, String[] synonyms) {
// according to synonyms To build a map
buildGraph(synonyms);
// Record the frequency of each word .
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 There are no such isolated points in
addNode(key);
}
// Traverse all connected components
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) {
// Get the smallest name
if (val.containsKey(name) && min.compareTo(name) > 0) min = name;
// The result is itself , Add all adjacent nodes .
int rs = val.getOrDefault(name, 0);
// Get all the next node
Set<String> next = graph.get(name);
// Don't go through the nodes .
graph.remove(name);
if (null == next) return rs;
for (String s : next) {
// Only the UN calculated node values are calculated .
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) {
// Add a node
addNode(node);
addNode(another);
// Set the edge
graph.get(node).add(another);
graph.get(another).add(node);
}
private void addNode(String node) {
if (!graph.containsKey(node)) graph.put(node, new HashSet<>());
}
}
summary
1) Find the connected component variant .
2) The concrete implementation of adjacency matrix .
notes : Connected components and union search sets ( initialization / Merge / Find the root node ) Precise connection , We can use the union search set solution .
reference
边栏推荐
- class path resource [classpath*:mapper/*.xml] cannot be opened because it does not exist
- 如何使用tensorboard add_histogram
- How applets and the industrial Internet complement each other
- Software testing -- Classification of tests
- Reprint: network loading framework - retrofit
- Nuxt SSR packaging and deployment
- 洞见数据价值,启迪数字未来,《数字化的力量》问世
- Hardware development notes (III): basic process of hardware development, making a USB to RS232 module (II): design principle diagram Library
- Programming dry goods │ PHP common method encapsulation
- C delegate
猜你喜欢

被八股文害惨了。。。。

Basic contents of external sorting

Xiuno修罗轻论坛仿知乎蓝简约响应式主题模板1.7+自适应PC+WAP端

Insight into the value of data, enlighten the digital future, and the power of digitalization came out

Reddit产品主管:Web3创作者必备的NFT会员实用指南

6月編程語言排行榜已出,這門語言要“封神”

Layout roadmap, the perfect combination of spatial layout and data visualization

目标检测、视觉弱监督学习、大脑多模态成像技术等CV综述来了!图像图形学发展年度报告综述专刊!

Win11怎么把桌面文件路径改到D盘
![Detailed explanation of C language [implicit type conversion] and [explicit type conversion]](/img/95/5acd2dd7b800b43435b52a70001a74.png)
Detailed explanation of C language [implicit type conversion] and [explicit type conversion]
随机推荐
Résolution de l'erreur de développement du système Kirin "erreur réelle: gl / gl.h: pas de fichier ou de répertoire"
SQL interview questions: top 15 questions in 2022
Qt文档阅读笔记-staticMetaObject解析与实例
软件项目律师尽职调查白皮书-全文19页,请与作者联系
Flag bit generation
[technical remarks] [reprint]analysis of several parameters of ffmpeg compressed video
Creation of mono
目标检测、视觉弱监督学习、大脑多模态成像技术等CV综述来了!图像图形学发展年度报告综述专刊!
Binary sort tree
Analysis of Eureka
Voir la valeur des données, éclairer l'avenir numérique, le pouvoir numérique est sorti
IPD chip shipments exceeded 1billion, and chips and semiconductors appeared in ims2022
Student management system experiment report -asp Net programming
Unity network development (I)
How to open a VIP account in flush? Is it safe?
6月编程语言排行榜已出,这门语言要“封神”
SQL tutorial: five SQL skills that data scientists need to master
Google AI big model lamda can one day replace the search engine? Google researcher: search can be re imagined as a two-way dialogue between users and languages
Win11 how to change the desktop file path to disk D
You have a chance, here is a stage