Introduction to Algorithms: graph traversal ---- depth-first search (DFS) and breadth-first search (BFS)

Introduction to Algorithms: graph traversal ---- depth-first search (DFS) and breadth-first search (BFS)

Graph traversal

1. FIG defined

Simply put, by a few small dots in FIG. (Called vertices) and the straight lines connecting these dots (called side) thereof.

Figure 2. Classification

FIG undirected graphs can be divided and digraph

  • Undirected graph
    Here Insert Picture Description
  • Directed graph
    Here Insert Picture Description

3. graph traversal algorithm

1. depth-first search (DFS)

Graph traversal DFS thought

First, a vertex is not visited as the starting vertex, go unvisited vertex along the edge of the current vertex; when there is no unvisited vertex, then back to a vertex, continue to test access to other vertices until all vertices have been visited. clearly, a depth-first traversal along a branch graph traversal until the end, and then back again the same manner traversing along one another, until all vertices have been visited so far.

Legend Profile

In the above example undirected graph, the search path for the FIG DFS:
Here Insert Picture Description
DFS route search is: 1-> 2-> 4-> 3-> 5

Code address

Undirected graph traversal DFS- Graphs and FIG.

2. The breadth-first search (BFS)

BFS graph traversal thought

First, a vertex not been accessed as a start vertex, access to all of its adjacent vertices, then each adjacent vertex, vertex and then access their adjacent not been accessed until all vertices have been visited too, traverse end.

Legend Profile

In the above example undirected graph, the search path for the next BFS in FIG:
Here Insert Picture Description
route BFS search is: 1-> 2-> 3-> 5-> 4

Code address

Undirected graph graph traversal BFS-

Published 155 original articles · won praise 15 · views 160 000 +

Guess you like

Origin blog.csdn.net/wangdamingll/article/details/105384100