Jac*_*ale 25 algorithm graph breadth-first-search data-structures
这是练习:
令v和w为有向图G =(V,E)中的两个顶点.设计线性时间算法以找到v和w之间的不同最短路径(不一定是顶点不相交)的数量.注意:G中的边缘未加权
对于这个消费税,我总结如下:
从以上几点来看,我有以下想法:
count最短路径的数量global level信息global level每次增加1,然后BFS达到一个新的水平shortest level最短路径的信息global level给shortest level和count++;global level等于shortest level,我count每次遇到w时都会增加.global level变得比大shortest level,我终止旅行,因为我正在寻找最短的路径而不是路径.我的算法是否正确?如果我做v到w然后w到v,那还是被认为是线性时间吗?
LiK*_*Kao 21
以下是对此的一些想法.
证明:如果有多条路径x通过同一个顶点进入,则显然有多种方式可以通过x.这很简单.现在让我们假设x每个顶点只有一种方式进入x(最大).
如果之前遇到过x,则当前路径都不能为另一条最短路径做出贡献.由于之前遇到过x,所以可以跟随的所有路径将比前一个最短路径长至少一个.因此,这些路径都不能对总和做出贡献.
这意味着我们最多只遇到一次节点并完成.所以正常的BFS就好了.
这可以编译成一个非常简单的算法,主要是BFS.
- Mark nodes as visited as usual with BFS.
- Instead of adding just nodes to the queue in the DFS add nodes plus number of incoming paths.
- If a node that has been visited should be added ignore it.
- If you find a node again, which is currently in the queue, do not add it again, instead add the counts together.
- Propagate the counts on the queue when adding new nodes.
- when you encounter the final, the number that is stored with it, is the number of possible paths.
Run Code Online (Sandbox Code Playgroud)
小智 9
你的算法在图表上打破了
* * * 1
/ \ / \ / \ / \
v * * * w
\ / \ / \ / \ /
* * * 2
Run Code Online (Sandbox Code Playgroud)
所有边缘从左向右指向.它计算两个路径,一是通过1和其他通过2,但两者1并2可以达到v八个不同的最短路径,共计十六个.
| 归档时间: |
|
| 查看次数: |
39918 次 |
| 最近记录: |