首页 > 编程语言 > 详细

二维链表数组,程序3.20

时间:2020-07-04 09:45:46      阅读:42      评论:0      收藏:0      [点我收藏+]

代码为

 1 #include <math.h>
 2 #include <stdio.h>
 3 #include <stdlib.h>
 4 //#include "Point.h"
 5 typedef struct node* link;
 6 
 7 typedef struct {
 8     float x;
 9     float y;
10 } point;
11 
12 
13 struct node { point p;  link next; };
14 link** grid; int G; float d; int cnt = 0;
15 float randFloat()
16 {
17     return 1.0 * rand() / RAND_MAX;
18 }
19 float distance( point a, point b)
20 {
21     float dx = a.x - b.x, dy = a.y - b.y;
22     return sqrt(dx * dx + dy * dy);
23 };
24 
25 link** malloc2d(int  r, int c)
26 {
27     int i;
28     link** t = (link **)malloc(r * sizeof(link*));
29     for(i = 0;i < r;i++)
30     t[i] = (link *)malloc(c * sizeof(link));
31     return t;
32 }
33 
34 
35 void gridinsert(float x, float y)
36 {
37     int i, j; link s;
38     int X = x * G + 1; int Y = y * G + 1;
39     link t = (link)malloc(sizeof * t);
40     t->p.x = x; t->p.y = y;
41     for (i = X - 1; i <= X + 1; i++)
42         for (j = Y - 1; j <= Y + 1; j++)
43             for (s = grid[i][j]; s != NULL; s = s->next)
44                 if (distance(s->p, t->p) < d) cnt++;
45     t->next = grid[X][Y]; grid[X][Y] = t;
46 }
47 int main(int argc, char* argv[])
48 {
49     int i, j, N = atoi(argv[1]);
50     d = atof(argv[2]); G = 1 / d;
51     grid = malloc2d(G + 2, G + 2);
52     for (i = 0; i < G + 2; i++)
53         for (j = 0; j < G + 2; j++)
54             grid[i][j] = NULL;
55     for (i = 0; i < N; i++)
56         gridinsert(randFloat(), randFloat());
57     printf("%d edges shorter than %f\n", cnt, d);
58     return 0;
59 }

 

二维链表数组,程序3.20

原文:https://www.cnblogs.com/hulianxingkong/p/13233612.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!