SoFunction
Updated on 2025-03-02

C# instance code to implement breadth-first search

1. Introduction to the algorithm

Breadth-First Search (BFS) is a graph search algorithm used to search target nodes in the data structure of a graph or tree.

The BFS starts from a given starting node and scales outwards layer by layer until the target node is found or the complete graph is traversed. Specifically, the BFS traverses nodes directly connected to the current node one by one according to the level, and adds these nodes to the queue to be searched. Then iterate through the nodes in the queue one by one, and add unvisited nodes directly connected to these nodes to the queue. This is repeated until the queue is empty or the target node is found.

The BFS algorithm can be used to solve many problems, such as finding the shortest path, detecting the ring in the graph, and generating the minimum spanning tree of the graph, etc. Its time complexity is O(V+E), where V is the number of vertices and E is the number of edges.

BFS algorithm has many application scenarios, such as friend recommendations in social networks, shortest path search for mazes, etc. Since BFS gradually expands searches at levels, BFS is often more efficient than depth-first searches when searching for shortest path problems. However, BFS needs to use a queue to save the nodes to be searched, so it may be larger than DFS in terms of space consumption.

2. Why learn breadth-first search algorithm:

  • The breadth-first search algorithm is an important graph search algorithm that can find the shortest path or solve problems in the graph.

  • The breadth-first search algorithm can traverse all nodes in the graph and search in a hierarchical manner, thus enabling systematic exploration of all possible paths or solutions.

  • Breadth-first search algorithms can be applied to a variety of problems, such as finding the shortest path, maze problems, interpersonal relationships in social networks, etc.

  • Learning breadth-first search algorithms can improve your understanding of graphs and are helpful in solving more complex graph-related problems.

  • Learning breadth-first search algorithms can improve programming skills and exercise the ability of problem solving and algorithm design.

3. What are the practical applications of breadth-first search algorithms in projects:

3.1 Web crawler:

Breadth-first search algorithms can be used for web crawlers to obtain information from the Internet. A crawler can start with a starting page, get all the links on the page, and add these links to the pending queue. Then, process the links in the queue in turn, obtaining more links until you go through the entire website.

3.2 Social network analysis:

Breadth-first search algorithms can be used in social network analysis to discover relationships between users and the overall structure of social networks. Starting from a user node, searching for all its directly connected users, then searching for connections for those users, and so on. This approach can help identify key users and communities.

3.3 Solution to the maze:

Breadth-first search algorithms can be used to solve maze problems. The maze can be regarded as a graph where each room is a node and the channel of each room is an edge. By using the breadth-first search algorithm, the shortest path from the start point to the end point can be found.

3.4 Operating system scheduling:

The breadth-first search algorithm can be applied in operating system scheduling algorithms to handle processes and resource allocation. Through the breadth-first search algorithm, it is possible to ensure that each process gets the corresponding time slice in order to use the system resources fairly.

3.5 Word game solution:

Breadth-first search algorithms can be used to solve word games, such as finding the shortest conversion sequence between two words. Through the breadth-first search algorithm, you can start with the starting word and gradually convert each word until the target word is found.

4. Implementation and explanation of breadth-first search algorithm:

Implementing Breadth-First Search (BFS) in C# usually involves using a queue (Queue). Breadth-first search is an algorithm used to traverse or search a tree or graph. It starts with the root node (or the starting node), explores the nodes as close as possible, and then gradually expands to the outer layer.

Here is a simple C# example showing how to traverse a graph using the breadth-first search algorithm (the graph is represented by an adjacency table here). Note that this example assumes that the graph is undirected and that the graph may contain rings.

using System;
using ;

class Program
{
    static void Main(string[] args)
    {
        // Adjacent table representation of the example graph        // The vertices of the graph are 0, 1, 2, 3, 4        Dictionary<int, List<int>> graph = new Dictionary<int, List<int>>()
        {
            { 0, new List<int> { 1, 2 } },
            { 1, new List<int> { 0, 3 } },
            { 2, new List<int> { 0, 3, 4 } },
            { 3, new List<int> { 1, 2 } },
            { 4, new List<int> { 2 } }
        };

        int startVertex = 0; // Start searching from vertex 0        BFS(graph, startVertex);
    }

    static void BFS(Dictionary<int, List<int>> graph, int startVertex)
    {
        Queue<int> queue = new Queue<int>();
        bool[] visited = new bool[]; // Mark whether the node has been accessed
        // Add the starting node to the queue and mark it as accessed        (startVertex);
        visited[startVertex] = true;

        while ( > 0)
        {
            int currentVertex = (); // Take out a node from the queue            (currentVertex + " "); // Processing node (here is the print node)
            // traverse all adjacent nodes of the current node            foreach (int neighbor in graph[currentVertex])
            {
                if (!visited[neighbor]) // If the adjacent node is not accessed                {
                    (neighbor); // Add adjoining nodes to the queue                    visited[neighbor] = true; // Mark as accessed                }
            }
        }
    }
}

In this example, we create a name calledgraphofDictionary<int, List<int>>to store the adjacency table representation of the graph. Each vertex of the graph is represented by an integer, and the adjacent nodes of the vertex are stored in a list.BFSThe function implements a breadth-first search algorithm. It uses a queue to store nodes to be accessed and uses a boolean arrayvisitedTo track which nodes have been accessed. The algorithm starts with the starting node, queues it and marks it as accessed. It then enters a loop that continuously takes nodes from the queue and accesses all its unvisited adjoining nodes, joins them to the queue and marks accessed. This process continues until the queue is empty, i.e. all reachable nodes have been accessed.

This is the article about C#’s example code to implement breadth-first search. For more related C#’s breadth-first search content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!