简体   繁体   中英

How to use a DFS algorithm to find the smallest product?

I've never used DFS before and I was wondering how you could use one to find the smallest product of a path if you were to traverse through the following "tree":

        3
      4   5
    7   6   4
  3   5   7   8
1   2   3   4   4

See comments below to clear any confusion(:

You need to construct a directed graph, where the nodes are the numbers, and each node has 2 edges to a number/node on the next level. The graph in this particular problem will be a directed acyclic graph.

Then, you just run DFS on the graph constructed. However, you will not keep track of/check whether you have visited a node before or not, since you want to revisit them. Instead, you only need to check whether the current node has 0 out-degree or node (since the nodes at the bottom will have 0 out-degree ), and update the current min when you reach the nodes at the bottom. (You may also keep track of the current depth, and update the current min when the depth is reached). We can do this for this particular problem, since all the products is the result of multiplying exactly 5 numbers, one from each level.

What I describe above is called tree search variant of DFS, compared to the normal graph-search variant where you keep track whether a node has been visited before. Tree search DFS will get stuck when there is a cycle in the graph, but since this is a directed acyclic graph, we will not run into such problem.


If the numbers are all non-negative , we can observe that: regardless of how we reach a node from the root, the optimal path ahead is going to be the same every time.

In such case, it is faster to work backward from the bottom nodes. For each pairs that are adjacent to the same "parent" node, pick the smaller one and multiply with the "parent" node. Keep doing so until you reach the root node, and you will get the result.


If the numbers can be positive or negative or 0 , you need to keep track of 4 numbers: negative product with the largest and smallest absolute value, largest and smallest positive product. And you also need to keep track of whether 0 product can be formed or not. The 2 largest absolute value are for the case of positive x negative . The 2 smallest absolute value are for the case of positive x positive or negative x negative . At the start of the algorithm, all those 5 fields are undefined.

The details of how to update are left to the readers. The result should be checked in the order: the negative number with the largest absolute value, 0, the positive number with the smallest absolute value. If the field is undefined, then skip it and check the next one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM