비용 산출을 위해 0-3-6-5
을 얻으려고합니다. 이전 배열의 출력은 -1-0-3-1
입니다. 방문 배열에 대해서는 1-1-1-1
입니다.클래스에 dijkstra의 알고리즘을 구현하려고합니다.
비용은 내 출력에 0-3-7-5
, 이전에는 -1-0-1-1
이됩니다. 가능한 경우 도와주세요.
필자는 7이 6 일 때 어디에서 왔는지를 알아 내려고 노력했다. C 언어로 코딩 한 것은 이번이 처음이었습니다.
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#define infinity 999
int main (void){
int dij[4][4] = {{0,3,8,6},
{3,0,4,2},
{8,4,0,1},
{6,2,1,0}};
int visit[4];
int cost[4];
int previous[4];
//filling the visit, cost, previous arrays
for(int j=0; j<4; j++){
visit[j] = 0;
cost[j] = infinity;
previous[j] = -1;
}//adding the values to the arrays
//node I am on
cost[0] = 0; //first position in the cost array is set to 0
int counter = 0; //counter for the while loop
int currentRow = 0; //checks for the rows holding th smallest value in the dij array
while(counter < 4){
int min = infinity; //min value is set to infinity at the beginning of program
for(int y=0; y<4; y++){
//if the cost at the current position in th cost array is < min and the node is not visited
if(cost[y] < min && visit[y] == 0){
min = cost[y];
currentRow = y;
}//if
visit[currentRow] = 1;
}//for loop for col of dij array.
//loop to look at the cost array to find the lowest cost unvisited node and set row to that index value
for(int x=0; x<4; x++){
if(visit[x] != 1){
if(min + dij[currentRow][x] < cost[x]){
cost[x] = min + dij[currentRow][x];
previous[x] = currentRow;
}
}
}
counter++;
}//while loop for x column of dij array.
모든 단계를 손으로 가능한 모든 단계를 걷고 코드 인쇄를 가진 시도하고 어디에서 볼 수 있나요 갈라진다. 아무도 당신을 위해 논리 오류를 디버깅할지 모르겠습니다. –
나는 그것이 7로 바뀌는 곳을 정확히 발견했다. 그러나 그 기분 좋은 길을 간다. 카운터가 1 일 때 currentRow = 1, min = 3, x = 1 일 때 7로 변경됩니다. 어떤 이유로 그 행이나 열에서 진행되지 않고 인덱스 3에서 2를 얻습니다. 이 프로그램에서 나는 인생을 염두에두고 있으며 전공을 떨어 뜨리거나 F.를 들으면서 매우 실망 스럽다. –
코드가 인덱스 dij [1] [3] 또는 dij [3] [1]에 도달 할 때마다 7을 얻는 데 필요한 4 대신에 2를 취하지 않습니다. –