当前位置:网站首页>Depth first traversal (DFS) and breadth first traversal (BFS)
Depth first traversal (DFS) and breadth first traversal (BFS)
2022-07-06 21:44:00 【HairLossException】
List of articles
Depth-first traversal
Depth first traversal starts from the initial vertex , The initial vertex may have an adjacent vertex , The strategy of depth first traversal is to visit the first adjacent vertex first , Then use the accessed adjacent vertex as the initial vertex to access its first adjacent vertex .
Depth first traversal steps
(1) Visit vertex v, And access points v Mark as accessed .
(2) Successively v Of the adjacent points that are not accessed , Depth first traversal of the graph ; Until the graph neutralizes v Vertices that have paths are all accessed .
(3) If there are still vertices in the graph that are not accessed , From a vertex that has not been visited , Do depth first traversal again , Until all the vertices in the graph have been visited .
↑↑↑( Above this wx official account )
Visual demonstration of data structure and Algorithm
Code
public class Graph {
/* Store a collection of vertices */
private ArrayList<String> vertexList;
/* Store the adjacency matrix corresponding to the graph */
private int[][] edges;
/* The number of edges */
private int numOfEdges;
/* Record whether a vertex has been accessed */
private boolean[] isVisited;
public static void main(String[] args) {
String[] vertexs = {
"A","B","C","D","E"};
/* Create a graph object */
Graph graph = new Graph(vertexs.length);
/* Add vertex */
for (String vertex:vertexs) {
graph.insertVertex(vertex);
}
/* Add edge */
graph.insertEdges(0,1,1);
graph.insertEdges(0,2,1);
graph.insertEdges(1,2,1);
graph.insertEdges(1,3,1);
graph.insertEdges(1,4,1);
System.out.println(" Depth-first traversal ");
graph.dfs();
}
public Graph(int n){
/* Initialize matrix and set */
edges = new int[n][n];
vertexList = new ArrayList<>(n);
isVisited = new boolean[n];
numOfEdges = 0;
}
/** * Get the subscript of the first adjacent vertex * @param index * @return If it exists, return the corresponding subscript; otherwise, return -1 */
public int getFirstNeighbor(int index){
for (int i = 0; i < vertexList.size(); i++) {
if (edges[index][i] > 0){
return i;
}
}
return -1;
}
/** * Get the adjacent vertex subscript that has not been accessed * @param v1 The current peak * @param v2 Vertices that have been visited * @return The subscript of the next adjacent vertex */
public int getNextNeighbor(int v1,int v2){
for (int j = v2+1; j < vertexList.size(); j++) {
if (edges[v1][j] > 0){
return j;
}
}
return -1;
}
/** * Depth-first traversal * @param isVisited Record whether the vertex has been visited * @param i Current vertex */
public void dfs(boolean[] isVisited,int i){
System.out.print(getValueByIndex(i)+"->");
isVisited[i] = true;
int neighbor = getFirstNeighbor(i);
while(neighbor != -1){
// Indicates that there are adjacent vertices
if (!isVisited[neighbor]){
/*neighbor Not interviewed */
dfs(isVisited,neighbor);
}
/*neighbor The vertex has been accessed */
neighbor = getNextNeighbor(i,neighbor);
}
}
/* heavy load dfs*/
public void dfs(){
/* Traverse all the vertices */
for (int i = 0; i < getNumOfVertex(); i++) {
if (!isVisited[i]){
dfs(isVisited,i);
}
}
}
/* Insert vertex */
public void insertVertex(String vertex){
vertexList.add(vertex);
}
/** * Insert edge * @param v1 Subscript of vertex in adjacency matrix * @param v2 Subscript of vertex in adjacency matrix * @param weight A weight */
public void insertEdges(int v1,int v2,int weight){
edges[v1][v2] = weight;
edges[v2][v1] = weight;
numOfEdges++;
}
/* Get the number of vertices */
public int getNumOfVertex(){
return vertexList.size();
}
/* According to the subscript index Get the corresponding data */
public String getValueByIndex(int index){
return vertexList.get(index);
}
}
Running results
Depth-first traversal
A->B->C->D->E
Process finished with exit cod
Breadth first traversal
The breadth first traversal of a graph is similar to the sequence traversal of a tree , Breadth first traversal requires a queue to maintain the order of visited vertices , In order to access the adjacent vertices of these vertices in this order .
Breadth first traversal steps
(1) Access the initial vertex v And mark the vertices v Has been interviewed .
(2) Put the vertex v The team .
(3) When the queue is not empty, take out the head node of the queue u, If the queue is empty, the algorithm ends .
(4) Find the header node u The unreachable adjacent vertex of .
(5) Queue the adjacent vertices that are not accessed and mark them as accessed .
(6) Jump to step 3 Until all the vertices in the graph have been visited .
Code
/** * Breadth first traversal * @param isVisited Whether the vertex has been accessed * @param i Current vertex */
public void bfs(boolean[] isVisited,int i){
int u; // The queue header node corresponds to the subscript
int neighbor; // Adjacency vertex
/* queue , Record the order of accessing the top and bottom */
LinkedList queue = new LinkedList();
System.out.print(getValueByIndex(i)+"->");
isVisited[i] = true;
queue.addLast(i);
while(!queue.isEmpty()){
/* Take out the coordinates of the queue head node */
u =(Integer) queue.removeFirst();
neighbor = getFirstNeighbor(u);
while(neighbor != -1){
// Have adjacent vertices
/* Judge whether you have visited */
if(!isVisited[neighbor]){
System.out.print(getValueByIndex(neighbor)+"->");
isVisited[neighbor] = true;
queue.addLast(neighbor);
}
/* Already visited */
neighbor = getNextNeighbor(u,neighbor);
}
}
}
/** * heavy load bfs * Let all vertices be traversed by breadth first */
public void bfs(){
for (int i = 0; i < getNumOfVertex(); i++) {
if (!isVisited[i]){
bfs(isVisited,i);
}
}
}
public static void main(String[] args) {
String[] vertexs = {
"A","B","C","D","E"};
/* Create a graph object */
Graph graph = new Graph(vertexs.length);
/* Add vertex */
for (String vertex:vertexs) {
graph.insertVertex(vertex);
}
/* Add edge */
graph.insertEdges(0,1,1);
graph.insertEdges(0,2,1);
graph.insertEdges(1,2,1);
graph.insertEdges(1,3,1);
graph.insertEdges(1,4,1);
System.out.println(" Breadth first traversal ");
graph.bfs();
}
Running results
Breadth first traversal
A->B->C->D->E
Process finished with exit code 0
边栏推荐
- The use method of string is startwith () - start with XX, endswith () - end with XX, trim () - delete spaces at both ends
- 1292_FreeROS中vTaskResume()以及xTaskResumeFromISR()的实现分析
- Quick news: the flybook players' conference is held online; Wechat payment launched "education and training service toolbox"
- 华为在多个行业同时出击,吓人的技术让欧美企业瑟瑟发抖
- ACdreamoj1110(多重背包)
- What about the spectrogram
- MySQL - 事务(Transaction)详解
- [redis design and implementation] part I: summary of redis data structure and objects
- Quick access to video links at station B
- Divide candy
猜你喜欢

The difference between break and continue in the for loop -- break completely end the loop & continue terminate this loop

Is it profitable to host an Olympic Games?

What can one line of code do?

Vit paper details

PostgreSQL 安装gis插件 CREATE EXTENSION postgis_topology
![[interpretation of the paper] machine learning technology for Cataract Classification / classification](/img/0c/b76e59f092c1b534736132faa76de5.png)
[interpretation of the paper] machine learning technology for Cataract Classification / classification
![[Li Kou brushing questions] one dimensional dynamic planning record (53 change exchanges, 300 longest increasing subsequence, 53 largest subarray and)](/img/1c/973f824f061d470a4079487d75f0d0.png)
[Li Kou brushing questions] one dimensional dynamic planning record (53 change exchanges, 300 longest increasing subsequence, 53 largest subarray and)

JPEG2000-Matlab源码实现

【力扣刷题】32. 最长有效括号

numpy 下载安装
随机推荐
Why does MySQL index fail? When do I use indexes?
Yyds dry inventory run kubeedge official example_ Counter demo counter
JS learning notes OO create suspicious objects
Start the embedded room: system startup with limited resources
Shake Sound poussera l'application indépendante de plantation d'herbe "louable", les octets ne peuvent pas oublier le petit livre rouge?
C# 如何在dataGridView里设置两个列comboboxcolumn绑定级联事件的一个二级联动效果
Redistemplate common collection instructions opsforhash (IV)
VIM basic configuration and frequently used commands
14年本科毕业,转行软件测试,薪资13.5K
红杉中国,刚刚募资90亿美元
华为在多个行业同时出击,吓人的技术让欧美企业瑟瑟发抖
Five wars of Chinese Baijiu
What about the spectrogram
R语言做文本挖掘 Part4文本分类
string的底层实现
在Pi和Jetson nano上运行深度网络,程序被Killed
Quick access to video links at station B
npm run dev启动项目报错 document is not defined
互联网快讯:吉利正式收购魅族;胰岛素集采在31省全面落地
启动嵌入式间:资源有限的系统启动