java有向图生成所有路径

一,需求:下图为一个有向图,需要生成所有路径。

二,数据结构

顶点

@Data
public class VertexDTO implements Serializable {
    /**
     * 是否属于当前路径
     */
    private Boolean currentPath;/**
     * 顶点id
     */
    private Long id;/**
     * 节点id
     */
    private Long nodeId;


}

@Data
public class EdgeDTO {
    /**
     * 出顶点
     */
    private Long fromVertexNo;
    /**
     * 入顶点
     */
    private Long toVertexNo;


}

实现

/**
     * 递归获取起始点的所有路径
     * @param path 临时路径
     * @param vertices 所有顶点
     * @param edges 所有边
     * @param currentVertexId 当前顶点
     * @param finalPath 最终路径
     */
    public static void getPathList(List<Long> path,
                                   List<VertexDTO> vertices,
                                   List<EdgeDTO> edges,
                                   Long currentVertexId,
                                   List<List<Long>> finalPath){
        //路径添加当前顶点
        path.add(currentVertexId);
        //判断当前顶点是否是终点
        List<VertexDTO> nextVertexList = getNextVertexList(currentVertexId, vertices, edges);
        //没有后续相邻顶点视为终点
        if (CollectionUtils.isNotEmpty(nextVertexList)){
            for (int i = 0; i < nextVertexList.size(); i++) {
                getPathList(path, vertices, edges, nextVertexList.get(i).getId(), finalPath);
            }
        } else {
            //当前路径加入结果路径集合
            List<Long> road = new ArrayList<>(path);
            finalPath.add(road);
        }
        //删除最后一位
        path.remove(path.size() - 1);
    }

    /**
     * 获取顶点的相邻顶点集合
     *
     * @param vertexId
     * @param vertices
     * @param edges
     * @return
     */
    public static List<VertexDTO> getNextVertexList(
            Long vertexId,
            List<VertexDTO> vertices,
            List<EdgeDTO> edges) {
        List<VertexDTO> nextVertextList = vertices.stream().filter(v -> {
            for (GrtEdgeDTO edge : edges) {
                if (edge.getFromVertexNo().equals(vertexId) && edge.getToVertexNo().equals(v.getId())) {
                    return true;
                }
            }
            return false;
        }).collect(Collectors.toList());
        return nextVertextList;
    }

 


 

posted @ 2022-08-31 10:13  蓝领笑笑生  阅读(624)  评论(0编辑  收藏  举报