가장자리/경로 당 비용이 포함 된 유향 그래프를 나타내는 링크 된 목록의 목록에서 최단 경로를 찾고 싶습니다.최단 경로 링크드리스트
다음과 같이 보일 것이다 출력, 그것은 나에게이 정점 0에서 다른 정점에 도착하는 날을 것입니다 비용을 알려줍니다
d[0 to 0] = 0
d[0 to 1] = 20
d[0 to 2] = 10
이것은 내가 내 목록을 채우는 방법입니다 테스트. 내 문제에 대한 지금
int vertex, int edgeCost;
: 나는 모든 다른 사람의 정점 V에서 최단 경로를 찾으려면
LinkedList<GraphData> g = new LinkedList[3];
for (int i = 0; i < 3; i++)
weight[i] = new LinkedList<GraphData>();
g[0].add(new GraphData(1, 20);
g[0].add(new GraphData(2, 10);
GraphData 클래스는 다음과 같이 보인다.
public static int[] shortestPaths(int v, LinkedList<GraphData>[] cost)
{
// get the set of vertices
int n = cost.length;
// dist[i] is the distance from v to i
int[] dist = new int[n];
// s[i] is true if there is a path from v to i
boolean[] s = new boolean[n];
// initialize dist
for(int i = 0; i < n; i++)
dist[i] = cost[v].get(i).getCost();
s[v] = true;
// determine n-1 paths from v
for (int j = 2 ; j < n ; j++)
{
// choose u such that dist[u] is minimal for all w with s[w] = false
// and dist[u] < INFINITY
int u = -1;
for (int k = 0; k < n; k++)
if (!s[k] && dist[k] < INFINITY)
// check if u needs updating
if (u < 0 || dist[k] < dist[u])
u = k;
if (u < 0)
break;
// set s[u] to true and update the distances
s[u]=true;
for (int k = 0; k < n; k++)
if (!s[k] && cost[u].get(k).getCost() < INFINITY)
if(dist[k] > dist[u] + cost[u].get(k).getCost())
dist[k] = dist[u] + cost[u].get(k).getCost();
// at this point dist[k] is the smallest cost path from
// v to k of length j.
}
return dist;
}
이 줄 dist [i] = cost [v] .get (i) .getCost(); "IndexOutOfBoundsException"을 던졌습니다.
내가 뭘 잘못하고 있는지 알겠습니까? 어떤 도움을 주시면 감사하겠습니다.
오프별로 한 오류처럼
dist
배열을 초기화 할 수 있음을 채울; 어쩌면 정점은 1부터 시작하여 인덱스가 0부터 시작하여 인덱싱됩니까? –나는 그것을 0에서한다. –
'LinkedList's에 어떤 거리 쌍 사이에 거리를 넣으시겠습니까? 그렇다면 2D 배열을 사용하지 않는 이유는 무엇입니까? 그렇다면 예외를 던진 줄이 매우 잘못되었습니다. (그럴 경우 좀 더 정교한 답을 쓸 것입니다.) –