#include <stdio.h>
#include <math.h>
#define MAX 1000
float calculate_distance(float x1, float y1,float x2, float y2) {
float x = x1-x2;
float y = y1-y2;
return sqrt(x*x + y*y);
}
float min_distance(float points[MAX][2], int n) {
float distance = 0.0;
int visited[MAX] = {0};
float start[2] = {points[0][0], points[0][1]};//this is start points!
visited[0] = 1;
for (int count = 1; count < n; count++) {
float min_dist = INFINITY;
float next[2] = {0};
// Find the nearest unvisited point
for (int i = 1; i < n; i++) {
if (!visited[i]) {
float temp = calculate_distance(start[0], start[1],points[i][0],points[i][1]);
if (temp < min_dist) {
// printf("dis is: %.2f\n", temp);
min_dist = temp;
next[0] = points[i][0];
next[1] = points[i][1];
// printf("realnext is: %.2f and %.2f\n", next[0],next[1]);
}
}
}
// Update the total distance and mark the point as visited
distance += min_dist;
visited[(int)(next[0])] = 1;
//printf("here is: %.2f and %.2f\n", start[0],start[1]);
//printf("next is: %.2f and %.2f\n", next[0],next[1]);
start[0] = next[0];
start[1] = next[1];
//printf("next is: %.2f and %.2f\n", start[0],start[1]);
}
return distance;
}
int main() {
// Test the function with sample data
float points[MAX][2] = {{1, 1}, {1, -1}, {-1, 1}, {-1, -1}};
int n = 4;
float result = min_distance(points, n);
printf("answer is: %.2f\n", result);
return 0;
}
c언어로 그냥 좌표 받아서 점들 최소로 잇는 함수 만드는 중인데 갑자기 넣지도 않은 염병할 -1,0점이 나옴 이거 대체 왜이래??
배열이 아니라 인덱스를 건들고 있잖아 ;
어디서??
visited[(int)(next[0])] = 1; 이 줄을 기점으로 갑자기 next[1]이 바뀌더라고
거기가 실제 좌표값이라 위치를 참조하니까
그런데 next0는 안바꾸ㅣ고 next1만 바뀔수가 있음??
visited[(int)(next[0])] = 1;를 int nearest_point_index = -1로 해서 visited[nearest_point_index] = 1; 하는 느낌적인 느낌?