-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraph.c
More file actions
129 lines (111 loc) · 2.1 KB
/
graph.c
File metadata and controls
129 lines (111 loc) · 2.1 KB
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
117
118
119
120
121
122
123
124
125
126
127
128
129
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{ int data; struct node* next; }node;
typedef struct list
{ node *head,*tail; }list;
void ins_end(list* l,int k)
{
node* temp=(node*)malloc(sizeof(node));
temp->data=k; temp->next=NULL;
if(l->head==NULL) l->head=temp;
else l->tail->next=temp;
l->tail=temp;
}
typedef struct graph
{ list* array; int size; int* visited; int* dist; }graph;
graph* create_graph(int size)
{
graph* te=(graph*)malloc(sizeof(graph));
te->array=(list*)malloc(size*sizeof(list));
te->visited=(int*)malloc(size*sizeof(int));
te->dist=(int*)malloc(size*sizeof(int));
te->size=size; int i=-1;
while(++i<size)
te->array[i].head=te->array[i].tail=NULL;
return te;
}
graph g1;
void add_edge(int a,int b)
{
if(a>=g1.size || b>=g1.size) return;
ins_end(&(g1.array[a]),b);
//ins_end(&(g1.array[b]),a);
}
void print()
{
int i;
for(i=0;i<g1.size;i++)
{
printf("%d: ",i);
node *te=g1.array[i].head;
for(te=g1.array[i].head;te!=NULL;te=te->next)
printf("%d ",te->data);
printf("\n");
}
}
void dfs_visit(int i)
{
node* te;
//g1.visited[i]=1;
for(te=g1.array[i].head;te!=NULL;te=te->next)
if(g1.visited[te->data]==0)
dfs_visit(te->data);
printf("-%d-",i);
g1.visited[i]=2;
}
void dfs()
{
int i;
for(i=0;i<g1.size;i++)
g1.visited[i]=0;
for(i=0;i<g1.size;i++)
if(g1.visited[i]==0)
dfs_visit(i);
printf("\n");
}
list queue;
int dequeue()
{
int ret=queue.head->data;
if(queue.head==queue.tail)
queue.head=queue.tail=NULL;
else queue.head=queue.head->next;
return ret;
}
void bfs()
{
int i; node* v;
for(i=0;i<g1.size;i++)
g1.dist[i]=-1;
ins_end(&queue,0);
g1.dist[0]=0;
while(queue.head!=NULL)
{
int u=dequeue();
for(v=g1.array[u].head;v!=NULL;v=v->next)
if(g1.dist[v->data]==-1)
{
printf("VISIT:%d-%d\n",u+1,v->data+1);
g1.dist[v->data]=g1.dist[u]+1;
ins_end(&queue,v->data);
}
}
}
int main()
{
g1=*create_graph(10);
add_edge(1,3);
add_edge(2,3);
add_edge(1,2);
add_edge(3,5);
add_edge(6,5);
add_edge(2,7);
add_edge(8,2);
add_edge(8,7);
add_edge(8,9);
dfs();
queue.head=queue.tail=NULL;
bfs();
print();
}