最小ヒープ内の 2 つのノード間の最短パスを見つけるために、小さなスニペットを作成しました。
public int shortestPath(int i, int j)
{
int path = 0;
int hi = Math.max(i, j);
int lo = i + j - hi;
while (hi > lo)
{
hi = hi / 2;
path++;
}
if (hi == lo) return path;
while (hi != lo)
{
if (lo > hi) lo = lo / 2;
else hi = hi / 2;
path++;
}
return path;
}
より良い平均的なケースでこれを行うより良い方法はありますか? ただ学ぶ。
編集:
int[] arr = {0, 1, 2, 3, 4, 5, 6, 7};
簡単にするために、この配列がバイナリ ヒープであるとしましょう。ルートは 1 で、たとえば 5 と 7 の間の最短パスは shortestPath(5, 7) で与えられます。