zoukankan      html  css  js  c++  java
  • 《算法导论》习题解答 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酱。这里是偶尔做做搬运工的水果君(^_^) )

  • 相关阅读:
    Oracle 数据块,文件块转换,查看数据块对像
    逆向与汇编视频(36课) IDA 使用
    VC++消息钩子编程
    VS2008中opengl配置
    BSP技术详解3有图有真相
    BSP技术详解1有图有真相
    oracle 跟踪文件和转储命令
    BSP技术详解2有图有真相
    Recognizing and Learning Object Categories 连接放送
    自学MVC看这里——全网最全ASP.NET MVC 教程汇总
  • 原文地址:https://www.cnblogs.com/java20130723/p/3212223.html
Copyright © 2011-2022 走看看