Leetcode practice search

Depth-first search and breadth-first search are widely used in trees and graphs, but their applications are far more than that.

BFS

 

Breadth-first search traverses layer by layer, and each layer traversal is the result of the previous layer traversal as a starting point, traversing all nodes that can be accessed at a distance. It should be noted that the traversed nodes cannot be traversed again.

level one:

  • 0 -> {6,2,1,5}

Second floor:

  • 6 -> {4}
  • 2 -> {}
  • 1 -> {}
  • 5 -> {3}

the third floor:

  • 4 -> {}
  • 3 -> {}

The nodes traversed in each layer are the same distance from the root node. Let di denote the distance between the i-th node and the root node, and deduce a conclusion: for node i traversed first and node j traversed later, di <= dj. Using this conclusion, the optimal solution problem such as the shortest path can be solved: the path traversed to the destination node is the shortest path for the first time. It should be noted that using BFS can only solve the shortest path of an unweighted graph, which means that the cost from one node to another node is recorded as 1.

The following issues need to be considered when the program implements BFS:

  • Queue: used to store the nodes obtained by each round of traversal;
  • Marking: For the traversed node, it should be marked to prevent repeated traversal.

1. Calculate the shortest path length from the origin to a specific point in the grid

1091. Shortest Path in Binary Matrix(Medium)

 

Guess you like

Origin www.cnblogs.com/coding-fairyland/p/12739656.html