如何反转邻接表?

问题描述

假设我的邻接列表如下:

0 : 1
1 : 0

相反,它应该为空,因为初始列表中有两个弧:

0:
1:

0 : 1
1 : 

成为

0 : 
1 : 0

一个例子:

0 : 
1 : 

成为

0 : 1
1 : 0

最后一个例子

0 : 1,4
1 : 0,4
2 : 0,1,3,4
3 : 
4 : 3,1

成为

0 : 2,3
1 : 2,3
2 : 
3 : 0,2,4
4 : 0,2

是否有算法可以做到这一点?

Graphe *Graphe::grapheInverse( void ){
    Graphe *r = new Graphe (_adjacences.size() );
    for (unsigned i = 0; i < _adjacences.size(); i++)
        for ( unsigned j = 0; j < _adjacences[i]->size(); j++ )
            if ( (*_adjacences[i])[j] == 1 ) // or 0 or 2 or 3 or 4 or ... like last example
                //r->addArcs( i,(*_adjacences[i])[j] ); //adds an arc from A to B
            
    return r;
}

解决方法

只需反转邻接矩阵即可。

如果您有0,请将其替换为1,反之亦然。仅排除对角线,始终在此处放置0。