简体   繁体   English

有向图的转置算法

[英]Transpose Algorithm for Directed Graphs

I am trying to write a simple algorithm to represent a reverse directed adjacency matrix.我正在尝试编写一个简单的算法来表示反向邻接矩阵。 I want this in in-place, with running time of Theta(n^2).我希望它就地运行,运行时间为 Theta(n^2)。

At first I had this:起初我有这个:

for i=1 to n
         for k=1 to n
               //Reverse the edges and update the new adjacency list
                  A_new[k][i] = A_old[i][k]
return A_new

However, I realized the inner for loop would cause a problem because if first loop is going 1..n and second going form 1..n, you will need to swap everything twice.但是,我意识到内部 for 循环会导致问题,因为如果第一个循环是 1..n,而第二个循环是 1..n,您将需要交换所有内容两次。

What would the inner for loop have to be to avoid this?为了避免这种情况,内部 for 循环必须是什么?

Your code is fine if you're returning a new matrix.如果您要返回一个新矩阵,则您的代码很好。 If you want to flip the matrix in place, then you iterate over the upper triangle, and swap each element with the lower triangle like this:如果您想将矩阵翻转到位,则遍历上三角形,并将每个元素与下三角形交换,如下所示:

for i=1 to n-1
    for j=i+1 to n
        temp = A[i][j];
        A[i][j] = A[j][i];
        A[j][i] = temp;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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