• 《算法导论》习题解答 Chapter 22.1-3(转置图)


    一、邻接表实现

    思路:一边遍历,一边倒置边,并添加到新的图中

    邻接表实现伪代码:

    for each u 属于 Vertex
    	for v 属于 Adj[u]
    		Adj1[v].insert(u);

    复杂度:O(V+E);

    输入:

    3 3
    a b
    b c
    c a

    源代码:

    package C22;
    
    import java.util.Iterator;
    
    public class C1_3{
    
    	public static Adjacent_List getTransposeGraph(Adjacent_List g){
    		Adjacent_List Gt = new Adjacent_List(g.getSize());
    		for(int u=0;u<g.getSize();u++){
    			Iterator<String> iter = g.getListByVertexIndex(u).iterator();
    			while(iter.hasNext()){
    				String vstr = iter.next();
    				Gt.addEdge(vstr , g.getVertexValue(u));	//添加导致边
    			}
    		}
    		return Gt;
    	}
    	public static void main(String[] args) throws Exception {
    		Adjacent_List adjlist = GraphFactory.getAdjacentListInstance("input\transpose_input.txt");
    		System.out.println("====原图===");
    		adjlist.printAllEdges();
    		Adjacent_List transposeGraph = getTransposeGraph(adjlist);
    		System.out.println("=====倒置图=====");
    		transposeGraph.printAllEdges();
    	}
    }


    二、邻接矩阵实现


    思路:遍历二维数组,并A'[i][j] = A[j][i];

    伪代码:

    for i = 1 to V
    	for j = 1 to V
    		A'[j][i] = A[i][j];

    复杂度:O(V^2);


    源代码:

    package C22;
    
    import java.util.Iterator;
    
    public class C1_3{
    
    	public static Adjacent_Matrix getTransposeMatrix(Adjacent_Matrix g){
    		Adjacent_Matrix Gt = new Adjacent_Matrix(g.getSize());
    		for(int i=0;i<g.getSize();i++){
    			for(int j=0;j<g.getSize();j++){
    				Gt.setEdge(g.getVertexValue(j), g.getVertexValue(i), g.getElement(i, j));
    			}
    		}
    		return Gt;
    	}
    	public static void main(String[] args) throws Exception {
    		Adjacent_Matrix adj_matrix = GraphFactory.getAdjacentMatrixInstance("input\transpose_input.txt");
    		adj_matrix.printAllEdges();
    		System.out.println("================");
    		Adjacent_Matrix Gt = getTransposeMatrix(adj_matrix);
    		Gt.printAllEdges();
    	}
    }
    



    原文点此索引目录。感谢xiazdong君 && Google酱。这里是偶尔做做搬运工的水果君(^_^) )

  • 相关阅读:
    Delphi IDE 设置
    我最喜欢的歌曲
    Window 常用文件
    Delphi TTable 组件
    Delphi TDatabase 组件
    c语言->和 .
    Shell 工具之 gawk
    Shell 工具之 sed
    Shell 语法之函数
    Shell 语法之信号与作业
  • 原文地址:https://www.cnblogs.com/java20130723/p/3212223.html
Copyright © 2020-2023  润新知