如何解决如何在无向图非基于零中获取从源到目标的路径计数?
我已尝试使用以下代码在无向图中查找可能的路径数。?但它给了我一个错误。如果我尝试使用评论部分,它工作正常。如果它只支持基于零索引的结构,那么克服这个问题的替代方法是什么?
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 举报,一经查实,本站将立刻删除。