CS 61B lab13

挣扎了一下,没有想出更好的办法(哈哈哈哈哈哈

 public UDGraph length2Paths() {
    UDGraph newGraph = new UDGraph(vertices);
    // Put your answer to Part I here.
    for(int i=0;i<vertices;i++){
        for(int j=0;j<vertices;j++){
            if(this.adjMatrix[i][j]){            
                for(int k=0;k<vertices;k++){
                    if(this.adjMatrix[j][k]){
                        newGraph.addEdge(i, k);
                    }
                }               
            }
        }
    }

    return newGraph;
  }

  /**
   *  Returns a new UDGraph with the same vertices as "this" UDGraph.
   *    The new graph has an edge (v, w) if and only if there is a path of
   *    length "length" from v to w in "this" graph.
   *  @param length the length of paths used to construct the new graph.
   *  @return the new UDGraph.
   */
  public UDGraph paths(int length) {
    UDGraph newGraph = new UDGraph(vertices);
    // Put your answer to Part II here.
   if(length==2){
        newGraph=length2Paths();
    }else if(length>2){
        for(int i=0;i<vertices;i++){
            for(int j=0;j<vertices;j++){
                if(paths(length-1).hasEdge(i, j)){
                    for(int k=0;k<vertices;k++){
                        if(hasEdge(j, k)){
                            newGraph.addEdge(i, k);
                        }
                    }
                }
            }
        }
    }

    return newGraph;
  }
View Code

原文地址:https://www.cnblogs.com/developerchen/p/7376069.html