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

转载于:https://www.cnblogs.com/java20130723/p/3212223.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值