Breadth First Search (BFS) Algorithm

Table of contents

algorithm thinking

Time Complexity and Space Complexity

Algorithm implementation

Algorithm pros and cons

Application field


algorithm thinking

The idea of ​​the breadth-first search (BFS) algorithm is to start from a certain starting vertex of the graph, first visit all the neighbor vertices of this vertex in turn, and then traverse all the vertices in the graph layer by layer according to the distance, and first visit the nearest vertex to the current vertex. apex, and then gradually expand outward. Specifically, the BFS algorithm is implemented by using a queue data structure. After visiting a vertex, its unvisited neighbors are added to the queue and marked as visited. Then take out the next unvisited vertex from the queue, and repeat the above process until the queue is empty.

Time Complexity and Space Complexity

The time complexity of the breadth-first search (BFS) algorithm is O(V+E), where V is the number of vertices and E is the number of edges. This is because in the worst case, all vertices and edges need to be visited to complete the traversal.

The BFS algorithm uses a queue data structure to store vertices to be accessed and neighbor vertices, so the space complexity depends on the number of elements stored in the queue. In the worst case, that is, when the graph is a complete binary tree, the number of elements that the BFS algorithm needs to store reaches the O(V) level, so the space complexity is also O(V).

Algorithm implementation

The following is a sample code for implementing the breadth-first search algorithm in C# language:

    /// <summary>
    /// 广度搜索算法
    /// </summary>
   public class BreadthFirstSearch
    {
        private int V;              // 图中节点的数量
        private List<int>[] adj;    // 存储邻接表表示的图

        public BreadthFirstSearch(int v)
        {
            V = v;
            adj = new List<int>[V];
            for (int i = 0; i < V; i++)
            {
                adj[i] = new List<int>();
            }
        }

        // 添加一条边
        public void AddEdge(int v, int w)
        {
            adj[v].Add(w);
        }

        // 查找从起点s到终点t的最短路径
        public List<int> BFS(int s, int t)
        {
            bool[] visited = new bool[V];
            int[] prev = new int[V];
            for (int i = 0; i < V; i++)
            {
                prev[i] = -1;
            }
            Queue<int> queue = new Queue<int>();
            visited[s] = true;
            queue.Enqueue(s);
            while (queue.Count > 0)
            {
                int v = queue.Dequeue();
                for (int i = 0; i < adj[v].Count; i++)
                {
                    int w = adj[v][i];
                    if (!visited[w])
                    {
                        visited[w] = true;
                        prev[w] = v;
                        queue.Enqueue(w);
                        if (w == t)
                        {
                            return GetPath(prev, s, t);
                        }
                    }
                }
            }
            return null;
        }

        // 根据prev数组生成路径
        private List<int> GetPath(int[] prev, int s, int t)
        {
            List<int> path = new List<int>();
            int x = t;
            while (x != s)
            {
                path.Add(x);
                x = prev[x];
            }
            path.Add(s);
            path.Reverse();
            return path;
        }
    }



        static void Main(string[] args)
        {

            BreadthFirstSearch g = new BreadthFirstSearch(6);
            g.AddEdge(0, 1);
            g.AddEdge(0, 2);
            g.AddEdge(1, 3);
            g.AddEdge(1, 4);
            g.AddEdge(2, 4);
            g.AddEdge(3, 5);
            g.AddEdge(4, 5);

            List<int> path = g.BFS(0, 5);
            foreach (int node in path)
            {
                Console.Write(node + " ");
            }
            Console.ReadLine();
        }

In the above sample code, a BreadthFirstSearch class is defined to represent the graph, which contains methods for adding edges and performing breadth-first search. In the Main function a graph with 6 vertices is created and 6 edges are added. Finally, the BFS method is called to perform a breadth-first search on the graph, starting from vertex 2. In the BFS method, a visited array is used to record the visited vertices and a queue queue is used to store the vertices to be visited. Every time a vertex is visited, its unvisited neighbors are added to the queue, and then the next unvisited vertex is taken out from the queue, and the above process is repeated until the queue is empty. 

Algorithm pros and cons

Advantages of breadth-first search algorithm:

  1. Can find the shortest path from the starting point to all other vertices, so it is more suitable for solving the shortest path problem than depth-first search.

  2. In some special cases, the efficiency of the BFS algorithm is higher than that of the DFS algorithm. For example, when the graph is relatively dense or the target node is relatively close to the starting node, the BFS algorithm is usually faster than the DFS algorithm.

  3. The BFS algorithm can be used to judge whether a graph is a bipartite graph, etc., and has a wide range of applications.

Disadvantages of breadth-first search algorithm:

  1. Space complexity can be high when dealing with larger graphs. In the worst case, that is, when the graph is a complete binary tree, the number of elements that the BFS algorithm needs to store reaches the O(V) level, so the space complexity is also O(V).

  2. For some graphs, the BFS algorithm may not be able to find the shortest path, because the algorithm can only find the shortest path from the starting point, and cannot guarantee that it is the shortest path in the entire graph. For example, the BFS algorithm cannot correctly calculate the shortest path in a graph with negatively weighted edges.

Application field

Breadth-first search algorithm (BFS) has a wide range of applications in many fields, the following are some common application areas:

  1. Image processing: BFS algorithm can be used in image segmentation, object detection, etc. For example, in a binary image, the BFS algorithm can be used to find all pixels connected to a given point.

  2. Natural Language Processing: BFS algorithm can be used to solve the problem of lexical relationship in language. For example, the BFS algorithm can be used to find all possible synonyms starting with a word.

  3. Game design: BFS algorithm can be used in path planning in games, AI behavior simulation, etc. For example, in complex terrain, the BFS algorithm can be used to find the shortest path to avoid obstacles.

  4. Web search: BFS algorithm can be used for page crawling and web page ranking of search engines. For example, on the Internet, you can use the BFS algorithm to find all websites related to keywords and rank them.

  5. Database query optimization: BFS algorithm can be used in query optimization in database optimization and other aspects. For example, in a relational database, you can use the BFS algorithm to find all related data tables and indexes.

  6. Machine Learning: The BFS algorithm can be used in decision trees, image classification, etc. For example, in decision tree classification, BFS algorithm can be used for feature selection and node splitting.

In summary, the BFS algorithm is a very general algorithm that can play a role in many fields, especially for solving the shortest path problem in a graph.

Guess you like

Origin blog.csdn.net/beenles/article/details/130729968