Skip to content

Commit

Permalink
update 22.1
Browse files Browse the repository at this point in the history
  • Loading branch information
zhuxiuwei committed Oct 18, 2016
1 parent 8aa299c commit 1057298
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 2 deletions.
4 changes: 2 additions & 2 deletions Chapter22_ElementaryGraphAlgorithms.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@ in-degree:O(V+E)
2. 遍历旧表的每个顶点a的Adj[a]
3. 每遍历到一个顶点b,往Adj[b]的尾部插入a,如果a!=b且a不在Adj[b]里出现过。

### 22.1-5 The **square** of a directed graph G=(V,E) is the graph G2 =(V,E2) such that (u,w) in E2 if and only if for some v in V, both(u,v) in E and(v,w) in E.That is,G2 contains an edge between u and w whenever G contains a path with exactly two edges between u and w. Describe efficient algorithms for computing G2 from G for both the adjacency-list and adjacency-matrix representations of G. Analyze the running times of your algorithms.

### 22.1-5 有向图G = (V, E)的**平方图**是图G2 = (V, E2),该图满足下列条件:(u, w)属于E2当且仅当v属于V,有(u, v)属于E,且(v, w)属于E。亦即,如果图G中顶点u和w之间存在着一条恰包含两条边的路径时,则G2必包含该边(u, w)。针对图G邻接表和邻接矩阵两种表示,分别写出根据G产生G2的有效算法,并分析所给出算法的运行时间。
[代码](https://github.com/zhuxiuwei/CLRS/blob/master/src/chap22_ElementaryGraphAlgo/Prac22_1_5_SquareGraph.java)



61 changes: 61 additions & 0 deletions src/chap22_ElementaryGraphAlgo/Prac22_1_5_SquareGraph.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package chap22_ElementaryGraphAlgo;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* 161018
* @author xiuzhu
* 22.1-5 有向图G = (V, E)的**平方图**是图G2 = (V, E2),该图满足下列条件:(u, w)属于E2当且仅当v属于V,有(u, v)属于E,且(v, w)属于E。
* 亦即,如果图G中顶点u和w之间存在着一条恰包含两条边的路径时,则G2必包含该边(u, w)。针对图G邻接表和邻接矩阵两种表示,分别写出根据G产生G2的有效算法,并分析所给出算法的运行时间。
*/
public class Prac22_1_5_SquareGraph {

/**
* @param g 有向图G的邻接矩阵表示. O(V^3)
* @return 平方图G2的邻接矩阵表示
*/
public int[][] transform(int[][] g){
if(g == null)
return null;

int[][] g2 = new int[g.length][g.length];
for (int i = 0; i < g.length; i++) {
for (int j = 0; j < g.length; j++) {
if(g[j][i] == 1){
for (int k = 0; k < g.length; k++) {
if(g[i][k] == 1)
g2[j][k] = 1;
}
}
}
}
return g2;
}

/**
* @param g 有向图G的邻接表表示
* @return 平方图G2的邻接表表示
*/
public Map<Integer, List<Integer>> transform(Map<Integer, List<Integer>> g){
if(g == null)
return null;

Map<Integer, List<Integer>> g2 = new HashMap<Integer, List<Integer>>();

for (Integer k: g.keySet()) {
List<Integer> neighbors = g.get(k);

}
return g2;
}

public static void main(String[] args) {
Prac22_1_5_SquareGraph p = new Prac22_1_5_SquareGraph();
System.out.println(Arrays.deepToString(p.transform(new int[][]{{0,1,1},{0,0,1},{0,0,0}})));
System.out.println(Arrays.deepToString(p.transform(new int[][]{{0,1,1},{0,0,1},{1,0,0}})));
}

}

0 comments on commit 1057298

Please sign in to comment.