当前位置:网站首页>Summary of leetcode BFS question brushing
Summary of leetcode BFS question brushing
2022-07-04 06:29:00 【sure00】
I haven't written a summary of brush questions during this period , Because of the discovery BFS It will be a little difficult to deal with the problem .
From the basic point of view ,BFS(breath first search) Width first search . Is to traverse layer by layer .
BFS Several main applications of :
1. Traversing the tree hierarchically .
2. Traversal of graph hierarchically .、
3. The array is traversed hierarchically .
For these three different applications , About the framework of problem solving ( General idea )
1. For the problem to traverse according to the hierarchy , This is simpler .
a. There is a direction between the upper node and the lower node in the tree , For example, the parent node will point to the child node .
b. Because there is direction , There will be no undirected graph that points around and points to itself .
Its general framework is as follows :
i. initialization queue( Traversal by level must use queue), For example root push To queue Go inside to initialize queue.
ii. Record the number of elements in the current layer , Out of the queue in turn . And put the left and right children out of the queue into the queue at the same time .
iii. Go through the descendants layer by layer , Know that the queue is empty .
For the problem of traversing the tree according to the hierarchy , The solution framework is fixed . Don't bother .
2. For the hierarchical traversal of graphs
These problems are somewhat complicated , In particular, undirected graphs . Deal with the data in advance .
1. To extract into each element neighbors data , Then you can traverse layer by layer neighbor.
2. To initialize queue, You have to find the initialization queue The data of . That is, the data to be accessed first , For example, the first course in the topic of course selection .
3. use BFS Layer by layer traversal neighbor, And check whether you have visited before . An undirected graph has no direction ,A yes B Neighbors of , meanwhile B It's also A Neighbors of . If you don't check the duplicate , It will lead to an endless cycle .
For example, the topic of course selection . Some courses must be completed before taking later courses .
Like the introduction to algorithms, you can only repair advanced algorithms or advanced databases after you finish it .
207. Course Schedule
The framework is as follows :
1. Create subsequent courses for each course
2. Create the entry level of each course ( Preface course ).
3. initialization queue The element of is in degree 0 Curriculum ( First course )
4. BFS Visit the courses to be taken next semester layer by layer ,. The completion of the first floor in the queue means that the courses of this semester have been completed , Subtract the entry of all subsequent courses pointed to by the previous course 1, It represents that the previous course in the course of next semester has been completed .
5. When the entry level of this course is 0, Represents that you have completed all the introductory courses . You can put the course in the queue , It means that this course has been completed since the beginning of this semester .
3、 ... and , For the coordinate system / Hierarchical traversal of arrays .
Such a topic is also similar to graph traversal , for instance , such as 2101. Detonate the Maximum Bombs
The topic is if a bomb explodes , All mines in the explosion range will explode . Then find out how many mines can explode at most at one time .
Steps are as follows :
1. Find out the other mines within the explosion range of each mine , That is, its follow-up mines .
2. Now we have to consider which mines to put queue in , Detonate first .
Because I don't know which mine detonates first, it will detonate more mines , So I can only try one by one .
But you can't try every one foolishly , When you light a thunder , The mines detonated in turn within the detonating range are also removed from the array of mines to be tried . In this way, the number of mines to be tried is much less .
But this topic uses BFS There is also a bad point in doing it , That is checking the weight .
unorder_set perhaps unorder_map I won't support it pair As key. For example, the positions of coordinate points or arrays are x,y Two figures .
This pair of data is used pair After packaging , There's no way pair Most of all key To apply hash.
These questions are best used DP To do it , In this way, the coordinate position can be recorded .
The code is as follows
class Solution {
public:
unordered_map<int, vector<int>> buildGraph(vector<vector<int>>& bombs)
{
unordered_map<int, vector<int>> graph;
for(int i=0;i<bombs.size();i++){
long ix= bombs[i][0];
long iy= bombs[i][1];
long ir= bombs[i][2];
for(int j=0;j<bombs.size();j++){
if(j == i)
continue;
long jx= bombs[j][0];
long jy= bombs[j][1];
if( (jx-ix)*(jx-ix) + (jy-iy)*(jy-iy) <= ir*ir )
graph[i].push_back(j);
}
}
return graph;
}
int detonateBombs(int start, unordered_map<int, vector<int>> neighbors)
{
int ret=1;
queue<int> myqueue;
unordered_set<int> bombed;
bombed.insert(start);
myqueue.push(start);
while(!myqueue.empty()){
int size = myqueue.size();
for(int i=0;i<size;i++){
int cur = myqueue.front();
myqueue.pop();
for(auto neighbor: neighbors[cur]){
if(bombed.find(neighbor) != bombed.end())
continue;
else {
myqueue.push(neighbor);
bombed.insert(neighbor);
ret++;
}
}
}
}
return ret;
}
int maximumDetonation(vector<vector<int>>& bombs) {
// build a graph which bombs in the range of bombs A.
// BFS each bombs to get all the other bombs.
// go through all bombs as start bombs.
unordered_map<int, vector<int>> graph = buildGraph(bombs);
int maxBombs=0;
int tmp=0;
for(int start =0;start<bombs.size();start++) {
tmp = detonateBombs(start, graph);
if(tmp > maxBombs)
maxBombs = tmp;
}
return maxBombs;
}
};
边栏推荐
- Uniapp custom environment variables
- JS get the attribute values nested in the object
- QT releases multilingual International Translation
- C language - Blue Bridge Cup - Snake filling
- Practical gadget instructions
- 70000 words of detailed explanation of the whole process of pad openvino [CPU] - from environment configuration to model deployment
- Yiwen unlocks Huawei's new cloud skills - the whole process of aiot development [device access - ESP end-to-side data collection [mqtt]- real time data analysis] (step-by-step screenshot is more detai
- Tf/pytorch/cafe-cv/nlp/ audio - practical demonstration of full ecosystem CPU deployment - Intel openvino tool suite course summary (Part 2)
- Matlab remainder
- Vant --- detailed explanation and use of list component in vant
猜你喜欢
ES6 模块化
Component、Container容器常用API详解:Frame、Panel、ScrollPane
740. Delete and get points
Yiwen unlocks Huawei's new cloud skills - the whole process of aiot development [device access - ESP end-to-side data collection [mqtt]- real time data analysis] (step-by-step screenshot is more detai
测试岗的中年危机该如何选择?是坚守还是另寻出路?且看下文
Learning multi-level structural information for small organ segmentation
70000 words of detailed explanation of the whole process of pad openvino [CPU] - from environment configuration to model deployment
报错cvc-complex-type.2.4.a: 发现了以元素 ‘base-extension‘ 开头的无效内容。应以 ‘{layoutlib}‘ 之一开头。
C language - Blue Bridge Cup - Snake filling
Bicolor case
随机推荐
JS flattened array of number shape structure
Inputstream/outputstream (input and output of file)
AWT介绍
Arcpy uses the updatelayer function to change the symbol system of the layer
Tree DP
STC8H开发(十二): I2C驱动AT24C08,AT24C32系列EEPROM存储
How to solve the component conflicts caused by scrollbars in GridView
Invalid bound statement (not found): com. example. mapper. TblUserRecordMapper. login
复合非线性反馈控制(二)
Fast power (template)
QT releases multilingual International Translation
JSON Web Token----JWT和傳統session登錄認證對比
如何避免 JVM 内存泄漏?
How to avoid JVM memory leakage?
ES6 modularization
对List进行排序工具类,可以对字符串排序
C language - Blue Bridge Cup - Snake filling
R统计绘图-随机森林分类分析及物种丰度差异检验组合图
云原生——上云必读之SSH篇(常用于远程登录云服务器)
Operator < <> > fool test case