你没有指定极点应该放在哪个列/行索引,所以在下面我将它们从75开始放在0,所以极点在列/行索引0,75,150,225 ,300,375(所以6极)。它可能不是你想到的,但它会让你开始。
#include "stdio.h" #include "math.h" double distance(double x, double y, double grid) { x = fmod(x, grid); y = fmod(y, grid); // <- these modulos makes us treat every interval like the interval 0...grid double dx = grid/2 - fabs(x -grid/2); double dy = grid/2 - fabs(y -grid/2); //printf("%3u %3u %f %f \n", x, y, dx, dy); return sqrt(dx*dx+dy*dy); } int main(void) { int i; int j; double grid[375][375]; for(i = 0; i < 375; i ++){ for(j = 0; j<375; j++){ grid[i][j] = distance(i, j, 75); printf("%3u %3u %f\n", i, j, grid[i][j]); } } }
如果你有两个网格 polePos[5][5] 和 grid[375][375] 您可以使用以下算法计算距离:
polePos[5][5]
grid[375][375]
double dist[375][375]; int pI = 0, pJ = 0; for (int gI = 0; gI < 375; gI++) { while (pI + 1 < 5 && abs(polePos[pI][pJ].x - grid[gI][0].x) > abs(polePos[pI + 1][pJ].x - grid[gI][0].x) { pI += 1; } for (int gJ = 0; gJ < 375; gJ++) { while (pJ + 1 < 5 && abs(polePos[pI][pJ].y - grid[gI][gJ].y) > abs(polePos[pI][pJ + 1].y - grid[gI][gJ].y) { pJ += 1; } dist[gI][gJ] = distance(polePos[pI][pJ], grid[gI][gJ]); } pJ = 0; }
那里 pI 和 pJ 包含当前网格点的最近极点。
pI
pJ
如果你的 格 和你的 极 是相关的,也许最好把它们放在同一个结构中。
#include <stdbool.h> typedef struct{ int x, y; bool pole; } Point;
你可以看到它像棋盘,每个案件可能有或没有一块。
您可以在使用天真或经典算法后使用 Dijkstra算法 , 贝尔曼 - 福特 , 一个* 为了确定你的一个极点的最短路径。