我浪费了 3 天时间
最终解决了一个图形问题
用于
寻找最短距离
使用 BFS
想分享经验。
When the (undirected for me) graph has
fixed distance (1, 6, etc.) for edges
#1
We can use BFS to find shortest path simply by traversing it
then, if required, multiply with fixed distance (1, 6, etc.)
#2
As noted above
with BFS
the very 1st time an adjacent node is reached, it is shortest path
#3
It does not matter what queue you use
deque/queue(c++) or
your own queue implementation (in c language)
A circular queue is unnecessary
#4
Number of elements required for queue is N+1 at most, which I used
(dint check if N works)
here, N is V, number of vertices.
#5
Wikipedia BFS will work, and is sufficient.
https://en.wikipedia.org/wiki/Breadth-first_search#Pseudocode
我已经失去了 3 天的时间尝试上述所有替代方案,一次又一次地验证和重新验证
他们不是问题。
(如果您发现以上 5 有任何问题,请尝试花时间寻找其他问题)。
更多解释来自下面的评论:
A
/ \
B C
/\ /\
D E F G
假设上面是您的图表
图表向下
对于 A,相邻的是 B & C
对于 B,相邻的是 D & E
对于 C,相邻的是 F & G
比如说,起始节点是A
当你到达 A, to, B & C 时,从 A 到 B & C 的最短距离是 1
当您通过 B 到达 D 或 E 时,到 A 和 D 的最短距离为 2 (A->B->D)
同样,A->E 为 2 (A->B->E)
另外,A->F & A->G 是 2
所以,现在节点之间的距离不是 1,如果它是 6,那么只需将答案乘以 6
例如,
如果每个之间的距离为 1,则 A->E 为 2 (A->B->E = 1+1)
如果每个之间的距离为 6,则 A->E 为 12 (A->B->E = 6+6)
是的,bfs 可以采用任何路径
但我们正在计算所有路径
如果你必须从 A 到 Z,那么我们从 A 到中间 I 的所有路径,由于会有很多路径,我们丢弃除最短路径之外的所有路径,然后继续最短路径到下一个节点J
同样,如果从 I 到 J 有多条路径,我们只取最短的一条
例如,
假设,
A -> 我有距离 5
(步骤)假设,I -> J 我们有多条路径,距离为 7 和 8,因为 7 是最短的
我们取 A -> J 为 5(A->I 最短)+ 8(现在最短)= 13
所以 A->J 现在是 13
我们现在重复上面的(STEP)J -> K 等等,直到我们到达 Z
阅读这部分,2到3遍,然后在纸上画,你一定会明白我在说什么,祝你好运