我在c ++(XCode)中制作Dijikstra算法。 我当时得到了exc_bad_access代码= 1:
for (k=0; k<M; k++){
input>>i>>j>>V;
Graf[i][j] = V;
}
整个代码:
#include <iostream>
#include <fstream>
int min(int[]);
int **Graf;
int *Label;
int *Active;
int i, j, k;
int Start, N, M, V, Last;
using namespace std;
int min(int array[]) {
int min, k, min_pos = -1;
min = 32767;
for (k=0; k<M; k++) {
if (array[k] < min && Active[k] == 1){
min = array[k];
min_pos = k;
}
}
return min_pos;
}
int main(){
ifstream input ("input.txt");
input>>N>>M>>Start>>Last;
if (!input){
cout << "File not found" << endl;
return 1;
}
Graf = new int *[N];
for (i=0; i<N; i++){
Graf[i] = new int [N];
}
for (i=0; i<N; i++){
for (j=0; j<N; j++){
Graf[i][j]=0;
}
}
Label = new int [N];
Active = new int [N];
for (i=0; i<N; i++){
Label[i] = 0;
Active[i] = 0;
}
for (k=0; k<M; k++){
input>>i>>j>>V;
Graf[i][j] = V;
}
for (i=0; i<M; i++){
Label[i] = 32767;
Active[Start] = 1;
}
Label[Start] = 0;
i = Start;
do
{
for (j=0; j<N; j++)
if (Graf[i][j] != 0 && Label[j] > Label[i] + Graf[i][j]){
Active[j] = 1;
Label[j] = Label[i] + Graf[i][j];
}
Active[i] = 0;
i=min(Label);
}
while (i != -1);
cout << Label[Last] << endl;
return 0;
}
我在某些日子里找错了,但找不到。
INPUT.TXT 5 9 0 4 0 0 5 2 4 0 0 0 0 7 0 6 5 0 0 9 1 15 2 7 9 0 0 12 4 0 1 0 0 8 0 6 15 12 8 0
答案 0 :(得分:0)
我相信你的错误在输入文件中:你读取i和j并使用它来访问你的数组,而不验证这些值是否在预期的范围内。
例如,如果您使用错误消息改进了您的疑问代码,例如:
for (k=0; k<M; k++){
input>>i>>j>>V;
if (i>=N || j>=N) {
cerr << "Bad Input for k="<<k<<": "<<i<<","<<j<<","<<V<<endl;
continue;
}
//assert(i<N && j<N); variant if you don't care for the values
Graf[i][j] = V;
}
您将获得以下结果:
Bad Input for k=3: 7,0,6
Bad Input for k=4: 5,0,0
Bad Input for k=5: 9,1,15
Bad Input for k=6: 2,7,9