Debian Codegraph @

lib/ortho/rawgraph.c

raw
1 /*************************************************************************
2 * Copyright (c) 2011 AT&T Intellectual Property
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the Eclipse Public License v1.0
5 * which accompanies this distribution, and is available at
6 * https://www.eclipse.org/legal/epl-v10.html
7 *
8 * Contributors: Details at https://graphviz.org
9 *************************************************************************/
10
11 #include "config.h"
12
13 #include <ortho/rawgraph.h>
14 #include <stddef.h>
15 #include <util/alloc.h>
16 #include <util/list.h>
17
18 #define UNSCANNED 0
19 #define SCANNING 1
20 #define SCANNED 2
21
22 rawgraph *make_graph(size_t n) {
23 rawgraph* g = gv_alloc(sizeof(rawgraph));
24 g->nvs = n;
25 g->vertices = gv_calloc(n, sizeof(vertex));
26 for(size_t i = 0; i < n; ++i) {
27 g->vertices[i].color = UNSCANNED;
28 }
29 return g;
30 }
31
32 void
33 free_graph(rawgraph* g)
34 {
35 for(size_t i = 0; i < g->nvs; ++i)
36 LIST_FREE(&g->vertices[i].adj_list);
37 free (g->vertices);
38 free (g);
39 }
40
41 void insert_edge(rawgraph *g, size_t v1, size_t v2) {
42 if (!edge_exists(g, v1, v2)) {
43 LIST_APPEND(&g->vertices[v1].adj_list, v2);
44 }
45 }
46
47 void remove_redge(rawgraph *g, size_t v1, size_t v2) {
48 LIST_REMOVE(&g->vertices[v1].adj_list, v2);
49 LIST_REMOVE(&g->vertices[v2].adj_list, v1);
50 }
51
52 bool edge_exists(rawgraph *g, size_t v1, size_t v2) {
53 return LIST_CONTAINS(&g->vertices[v1].adj_list, v2);
54 }
55
56 typedef LIST(size_t) int_stack_t;
57
58 static int DFS_visit(rawgraph *g, size_t v, int time, int_stack_t *sp) {
59 vertex* vp;
60
61 vp = g->vertices + v;
62 vp->color = SCANNING;
63 const adj_list_t adj = vp->adj_list;
64 time = time + 1;
65
66 for (size_t i = 0; i < LIST_SIZE(&adj); ++i) {
67 const size_t id = LIST_GET(&adj, i);
68 if(g->vertices[id].color == UNSCANNED)
69 time = DFS_visit(g, id, time, sp);
70 }
71 vp->color = SCANNED;
72 LIST_PUSH_BACK(sp, v);
73 return time + 1;
74 }
75
76 void
77 top_sort(rawgraph* g)
78 {
79 int time = 0;
80 int count = 0;
81
82 if (g->nvs == 0) return;
83 if (g->nvs == 1) {
84 g->vertices[0].topsort_order = count;
85 return;
86 }
87
88 int_stack_t sp = {0};
89 LIST_RESERVE(&sp, g->nvs);
90 for(size_t i = 0; i < g->nvs; ++i) {
91 if(g->vertices[i].color == UNSCANNED)
92 time = DFS_visit(g, i, time, &sp);
93 }
94 while (!LIST_IS_EMPTY(&sp)) {
95 const size_t v = LIST_POP_BACK(&sp);
96 g->vertices[v].topsort_order = count;
97 count++;
98 }
99 LIST_FREE(&sp);
100 }