aboutsummaryrefslogtreecommitdiff
path: root/CS2501/graph.c
blob: 75d23535ddb75086b9dbd1480e2b9285186ed14f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#include <stdio.h>
#include <stdlib.h>

typedef struct agraph{
  int matrix[100][100];
} graph;

extern graph *g = 0;

void  init_graph()
{
  int i;
  g = malloc(sizeof(graph));
  for (i = 0; i < 100; i++){
    g->matrix[i][i] = -1;
  }
}

int adjacent(x,y)
int x,y;
{
  return g->matrix[x][y];
}

int* neighbors(x)
int x;
{
  int i, j;
  j = 1;
  for(i = 0; i < 100; i++)
  {
    if(g->matrix[x][i]){
      j++;
    }
  }
  int *y;
  y = calloc(j * sizeof(int));
  j = 0;
  for(i = 0; i < 100; i++) {
    if (g->matrix[x][i]){
      y[j++] = i;
    }
  }
  return y;
}

int add_vertex(x)
int x;
{
  if(!g){
	init_graph();
  }
  if (g->matrix[x][x] == -1){
    g->matrix[x][x] = 0;
    return 1;
  }
  return 0;
}

int remove_vertex(x)
int x;
{
  if(g->matrix[x][x] == -1){
    return 0;
  }
  int i;
  for(i = 0; i < 100; i++){
    g->matrix[x][i] = 0;
    g->matrix[i][x] = 0;
    }
  return 1;
}

int add_edge(x,y)
int x,y;
{
  if (g->matrix[x][y]){
    return 0;
  }

  g->matrix[x][y] = 1;
  return 1;
}

int remove_edge(x,y)
int x,y;
{
  if(g->matrix[x][y]){
    g->matrix[x][y] = 0;
    return 1;
  }
  return 0;

}

void printEdges()
{
  printf("Edges: \n" );
  int i,j;
  for (i = 0; i < 100; i++){
    for(j = 0; j < 100; j++){
      if(g->matrix[i][j] == 1)
        printf("\t%d -> %d\n", i, j);
    }
  }
}

void printVertices()
{
  printf("Vertices:\n");
  int i;
  for(i = 0; i <100; i++)
    if(g->matrix[i][i] != -1)
      printf("\t%d\n", i);

}