圖的算法——求兩頂點間的全部路徑

//求頂點start到end之間步數不超過maxStops步的全部路徑
public int numStops(int start, int end, int maxStops) throws Exception {
        boolean[] visited = new boolean[listDG.mVexs.length];
        for (int i = 0; i < listDG.mVexs.length; i++) {
            visited[i] = false;
        }
        return findRoutes(visited, start, end, 0, maxStops);
    }

    private int findRoutes(boolean[] visited, int start, int end, int depth, int maxStops) throws Exception {
        int routes = 0;
        ListDG.ENode eNode = listDG.mVexs[start].firstEdge;
        visited[start] = true;
        while (eNode != null) {
            depth += 1;
            if (depth <= maxStops) {
                if (eNode.ivex == end) {
                    routes++;
                    visited[eNode.ivex]=true;
                    eNode =eNode.nextEdge;
                    continue;
                } else if (!visited[eNode.ivex]) {
                    routes += findRoutes(visited, eNode.ivex, end, depth, maxStops);
                    depth--;
                }
            } else {
                depth--;
            }
            eNode = eNode.nextEdge;
        }
        visited[start] = false;
        return routes;
    }
相關文章
相關標籤/搜索