如何在无向图非基于零中获取从源到目标的路径计数?

问题描述

我已尝试使用以下代码无向图中查找可能的路径数。?但它给了我一个错误。如果我尝试使用评论部分,它工作正常。如果它只支持基于零索引的结构,那么克服这个问题的替代方法是什么?

import java.util.LinkedList;

public class CountPaths {

static int paths = 0;

static class Graph {
    int vertices;
    LinkedList<Integer>[] adjList;

    Graph(int vertices) {
        this.vertices = vertices;
        adjList = new LinkedList[vertices];
        for (int i = 0; i < vertices; i++) {
            adjList[i] = new LinkedList<>();
        }
    }

    public void addEgde(int source,int destination) {
        adjList[source].addFirst(destination);
    }

    public void countPaths(int source,int destination) {
        count(source,destination);
        System.out.println("Source : " + source + " & Destination : " + destination + " Paths :" + paths);
    }

    public void count(int start,int destination) {
        if (start == destination) {
            paths++;
        } else {
            for (int i = 0; i < adjList[start].size(); i++) {
                int ajdacentVertex = adjList[start].get(i);
                count(ajdacentVertex,destination);
            }
        }
    }
}

public static void main(String[] args) {
    /** 
    //This section is works fine
    int vertices = 6;
    
    Graph graph = new Graph(vertices);
    graph.addEgde(0,1);
    graph.addEgde(0,2);
    graph.addEgde(1,3);
    graph.addEgde(3,4);
    graph.addEgde(2,3);
    graph.addEgde(4,5);
    
    int source = 0;
    int destination = 5;
    */
    int vertices = 4;
    
    Graph graph = new Graph(vertices);
    graph.addEgde(1,2);
    graph.addEgde(2,1);
    graph.addEgde(4,1);
    
    int source = 1;
    int destination = 4;
    
    
    graph.countPaths(source,destination);
}

}

错误如下

Exception in thread "main" java.lang.Arrayindexoutofboundsexception: Index 4 out of bounds for length 4
    at CountPaths$Graph.addEgde(CountPaths.java:22)
    at CountPaths.main(CountPaths.java:63)

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)