Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemath
GitHub Repository: sagemath/sagelib
Path: blob/master/sage/graphs/planarity/graphColorVertices.c
4076 views
1
/*
2
Planarity-Related Graph Algorithms Project
3
Copyright (c) 1997-2010, John M. Boyer
4
All rights reserved. Includes a reference implementation of the following:
5
6
* John M. Boyer. "Simplified O(n) Algorithms for Planar Graph Embedding,
7
Kuratowski Subgraph Isolation, and Related Problems". Ph.D. Dissertation,
8
University of Victoria, 2001.
9
10
* John M. Boyer and Wendy J. Myrvold. "On the Cutting Edge: Simplified O(n)
11
Planarity by Edge Addition". Journal of Graph Algorithms and Applications,
12
Vol. 8, No. 3, pp. 241-273, 2004.
13
14
* John M. Boyer. "A New Method for Efficiently Generating Planar Graph
15
Visibility Representations". In P. Eades and P. Healy, editors,
16
Proceedings of the 13th International Conference on Graph Drawing 2005,
17
Lecture Notes Comput. Sci., Volume 3843, pp. 508-511, Springer-Verlag, 2006.
18
19
Redistribution and use in source and binary forms, with or without modification,
20
are permitted provided that the following conditions are met:
21
22
* Redistributions of source code must retain the above copyright notice, this
23
list of conditions and the following disclaimer.
24
25
* Redistributions in binary form must reproduce the above copyright notice, this
26
list of conditions and the following disclaimer in the documentation and/or
27
other materials provided with the distribution.
28
29
* Neither the name of the Planarity-Related Graph Algorithms Project nor the names
30
of its contributors may be used to endorse or promote products derived from this
31
software without specific prior written permission.
32
33
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
34
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
35
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
36
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
37
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
38
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
39
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
40
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
41
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
42
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
43
*/
44
45
#include "graphColorVertices.h"
46
#include "graphColorVertices.private.h"
47
48
extern int COLORVERTICES_ID;
49
50
#include "graph.h"
51
52
#if 0
53
#include <malloc.h>
54
#else
55
#if !defined(_XOPEN_SOURCE) && !defined(_ISOC99_SOURCE)
56
#define _XOPEN_SOURCE 600
57
#endif
58
#include <stdlib.h> /* ISO C99 also defines malloc() to be there. */
59
#endif
60
#include <string.h>
61
#include <stdio.h>
62
63
extern void _FillVisitedFlags(graphP theGraph, int FillValue);
64
extern int _TestSubgraph(graphP theSubgraph, graphP theGraph);
65
66
extern void _ColorVertices_Reinitialize(ColorVerticesContext *context);
67
68
/* Private functions exported to system */
69
70
void _AddVertexToDegList(ColorVerticesContext *context, graphP theGraph, int v, int deg);
71
void _RemoveVertexFromDegList(ColorVerticesContext *context, graphP theGraph, int v, int deg);
72
int _AssignColorToVertex(ColorVerticesContext *context, graphP theGraph, int v);
73
74
/* Private functions */
75
76
int _GetVertexToReduce(ColorVerticesContext *context, graphP theGraph);
77
int _IsConstantTimeContractible(ColorVerticesContext *context, int v);
78
int _GetContractibleNeighbors(ColorVerticesContext *context, int v, int *pu, int *pw);
79
80
/********************************************************************
81
gp_ColorVertices()
82
83
This is the entry point for requesting a vertex coloring by the
84
the minimum degree selection method.
85
86
The call pattern is to simply invoke this function on a graph to
87
color it or recolor it after some mutations. It will invoke
88
gp_AttachColorVertices() to attach the auxiliary data needed to
89
performing the coloring, and the attachment short-circuits if
90
already done.
91
92
After calling this function, call gp_ColorVertices_GetColors() to
93
obtain the colors or gp_Write() to save the colors. To read a saved
94
coloring, use gp_AttachColorVertices() then gp_Read().
95
96
Returns OK on success, NOTOK on failure
97
********************************************************************/
98
#include "platformTime.h"
99
100
int gp_ColorVertices(graphP theGraph)
101
{
102
ColorVerticesContext *context = NULL;
103
int v, deg;
104
int u=0, w=0, contractible;
105
106
// Attach the algorithm if it is not already attached
107
if (gp_AttachColorVertices(theGraph) != OK)
108
return NOTOK;
109
110
// Ensure there is enough stack to perform this operation.
111
// At a maximum, the graph reduction will push 7N+M integers.
112
// One integer is pushed per edge that is hidden. Plus, whether
113
// a vertex is hidden or identified with another vertex, 7 integers
114
// are used to store enough information to restore it.
115
if (sp_NonEmpty(theGraph->theStack))
116
return NOTOK;
117
118
if (sp_GetCapacity(theGraph->theStack) < 7*theGraph->N + theGraph->M)
119
{
120
stackP newStack = sp_New(7*theGraph->N + theGraph->M);
121
if (newStack == NULL)
122
return NOTOK;
123
sp_Free(&theGraph->theStack);
124
theGraph->theStack = newStack;
125
}
126
127
// Get the extension context and reinitialize it if necessary
128
gp_FindExtension(theGraph, COLORVERTICES_ID, (void *)&context);
129
130
if (context->color[0] > -1)
131
_ColorVertices_Reinitialize(context);
132
133
// Initialize the degree lists, and provide a color for any trivial vertices
134
for (v = 0; v < theGraph->N; v++)
135
{
136
deg = gp_GetVertexDegree(theGraph, v);
137
_AddVertexToDegList(context, theGraph, v, deg);
138
139
if (deg == 0)
140
context->color[v] = 0;
141
}
142
143
// Initialize the visited flags so they can be used during reductions
144
_FillVisitedFlags(theGraph, 0);
145
146
// Reduce the graph using minimum degree selection
147
while (context->numVerticesToReduce > 0)
148
{
149
v = _GetVertexToReduce(context, theGraph);
150
151
// Find out if v is contractible and the neighbors to contract
152
contractible = _GetContractibleNeighbors(context, v, &u, &w);
153
154
// Remove the vertex from the graph. This calls the fpHideEdge
155
// overload, which performs the correct _RemoveVertexFromDegList()
156
// and _AddVertexToDegList() operations on v and its neighbors.
157
if (gp_HideVertex(theGraph, v) != OK)
158
return NOTOK;
159
160
// If v was contractibile, then identify u and w
161
if (contractible)
162
{
163
if (gp_IdentifyVertices(theGraph, u, w, NIL) != OK)
164
return NOTOK;
165
}
166
}
167
168
// Restore the graph one vertex at a time, coloring each vertex distinctly
169
// from its neighbors as it is restored.
170
context->colorDetector = (int *) calloc(theGraph->N, sizeof(int));
171
if (context->colorDetector == NULL)
172
return NOTOK;
173
174
if (gp_RestoreVertices(theGraph) != OK)
175
return NOTOK;
176
177
free(context->colorDetector);
178
context->colorDetector = NULL;
179
180
return OK;
181
}
182
183
/********************************************************************
184
_AddVertexToDegList()
185
186
This function adds vertex v to degree list deg.
187
The current method simply appends the vertex to the degree list.
188
189
This method will be improved later to handle the degree 5 list
190
specially by prepending those degree 5 vertices that have two
191
non-adjacent neighbors with a constant degree bound. These vertices
192
can be specially handled by identifying the non-adjacent neighbors
193
during reduction so that the neighborhood of v receives only three
194
colors. This ensures that all planar graphs use at most 5 colors.
195
Matula, Shiloach and Tarjan (1980) introduced this contraction
196
method, and the tighter degree bound on the neighbors used in this
197
implementation is due to Frederickson (1984).
198
********************************************************************/
199
200
void _AddVertexToDegList(ColorVerticesContext *context, graphP theGraph, int v, int deg)
201
{
202
if (deg > 0)
203
{
204
if (_IsConstantTimeContractible(context, v))
205
context->degListHeads[deg] = LCPrepend(context->degLists, context->degListHeads[deg], v);
206
else
207
context->degListHeads[deg] = LCAppend(context->degLists, context->degListHeads[deg], v);
208
209
context->numVerticesToReduce++;
210
}
211
context->degree[v] = deg;
212
}
213
214
/********************************************************************
215
_GetVertexDegree()
216
********************************************************************/
217
218
int _GetVertexDegree(ColorVerticesContext *context, int v)
219
{
220
return context->degree[v];
221
222
// We cache vertex degree values because the API function is O(deg(v)),
223
// which would make this algorithm implementation have quadratic behavior
224
// in the worst case
225
//
226
// return gp_GetVertexDegree(context->theGraph, v);
227
}
228
229
/********************************************************************
230
_IsConstantTimeContractible()
231
Wrapper function that just returns the result of _GetContractibleNeighbors()
232
Return TRUE if v is degree 5 and has a pair of non-adjacent neighbors
233
of degree 7 or lower; FALSE otherwise.
234
********************************************************************/
235
236
int _IsConstantTimeContractible(ColorVerticesContext *context, int v)
237
{
238
int u, w;
239
return _GetContractibleNeighbors(context, v, &u, &w);
240
}
241
242
/********************************************************************
243
_GetContractibleNeighbors()
244
Wrapper function that just returns the result of _GetContractibleNeighbors()
245
246
This function returns TRUE if the vertex v is degree 5 and has two
247
non-adjacent neighbors of degree at most 7. In 1980, Matula, Shiloach
248
and Tarjan proved the sequential contraction method of five-coloring
249
planar graphs could run in linear time based on deleting any vertices
250
less than degree 5 and, if none exist, contracting a degree 5 vertex
251
with two non-adjacent neighbors of degree at most 11. In 1984,
252
Greg N. Frederickson improved the result to 7.
253
254
When a vertex is being added to the degree list, it is appended
255
unless this function returns TRUE, in which case it is placed
256
at the front of the degree 5 list.
257
When a vertex is removed from a degree list for reduction, it is
258
tested again, and if this function returns TRUE, then two non-adjacent
259
neighbors of degree at most 7 are found. The vertex is hidden in
260
either case, but if the neighbors were found, then they are
261
identified. In the recursion, the neighbors will get the same
262
color so that when the vertex is restored, its neighborhood has at
263
most four colors. The vertex takes the fifth color.
264
Hence, planar graphs are colored with at most five colors. Non-planar
265
graphs are still colored, but perhaps with more than five colors since
266
the 5 list may become empty or may not start with a constant time
267
contractible vertex (in which case we stick with the constant time
268
per edge deletion only).
269
270
This function operates in constant time, so it only finds a pair of
271
contractible neighbors for degree 5 vertices, it determines the degree
272
of all neighbors in constant time, it determines whether each pair of
273
low degree neighbors is non-adjacent in constant time, and the degree
274
bound on the pair of neighbors returned ensures that they can be
275
identified (including removal of duplicate edges) in constant time.
276
277
Return TRUE if v is degree 5 and has a pair of non-adjacent neighbors
278
of degree 7 or lower; FALSE otherwise.
279
280
Also returns the two neighbors found if TRUE is returned. The pointer
281
variables are not altered in the FALSE case.
282
********************************************************************/
283
284
int _GetContractibleNeighbors(ColorVerticesContext *context, int v, int *pu, int *pw)
285
{
286
int lowDegreeNeighbors[5], i, j, n=0, J;
287
graphP theGraph = context->theGraph;
288
289
// This method is only applicable to degree 5 vertices
290
if (_GetVertexDegree(context, v) != 5)
291
return FALSE;
292
293
// Get all neighbors of degree at most 7
294
J = gp_GetFirstArc(theGraph, v);
295
while (gp_IsArc(theGraph, J))
296
{
297
if (_GetVertexDegree(context, theGraph->G[J].v) <= 7)
298
lowDegreeNeighbors[n++] = theGraph->G[J].v;
299
J = gp_GetNextArc(theGraph, J);
300
}
301
302
// Seek the pair of *non-adjacent* low degree neighbors
303
for (i=0; i < (n-1); i++)
304
for (j=i+1; j < n; j++)
305
if (!gp_IsNeighbor(theGraph, lowDegreeNeighbors[i], lowDegreeNeighbors[j]))
306
{
307
*pu = lowDegreeNeighbors[i];
308
*pw = lowDegreeNeighbors[j];
309
return TRUE;
310
}
311
312
// The desired pair of neighbors was not found
313
return FALSE;
314
}
315
316
317
/********************************************************************
318
_RemoveVertexFromDegList()
319
********************************************************************/
320
321
void _RemoveVertexFromDegList(ColorVerticesContext *context, graphP theGraph, int v, int deg)
322
{
323
if (deg > 0)
324
{
325
context->degListHeads[deg] = LCDelete(context->degLists, context->degListHeads[deg], v);
326
context->numVerticesToReduce--;
327
}
328
}
329
330
/********************************************************************
331
_GetVertexToReduce()
332
********************************************************************/
333
334
int _GetVertexToReduce(ColorVerticesContext *context, graphP theGraph)
335
{
336
int v = NIL, deg;
337
338
for (deg = 1; deg < theGraph->N; deg++)
339
{
340
if (context->degListHeads[deg] != NIL)
341
{
342
// Get the first vertex in the list
343
v = context->degListHeads[deg];
344
break;
345
}
346
}
347
348
return v;
349
}
350
351
/********************************************************************
352
_AssignColorToVertex()
353
********************************************************************/
354
355
int _AssignColorToVertex(ColorVerticesContext *context, graphP theGraph, int v)
356
{
357
int J, w, color;
358
359
// Run the neighbor list of v and flag all the colors in use
360
J = gp_GetFirstArc(theGraph, v);
361
while (gp_IsArc(theGraph, J))
362
{
363
w = theGraph->G[J].v;
364
context->colorDetector[context->color[w]] = 1;
365
366
J = gp_GetNextArc(theGraph, J);
367
}
368
369
// Find the least numbered unused color and assign it to v
370
// Note that this loop never runs more than deg(v) steps
371
for (color = 0; color < theGraph->N; color++)
372
{
373
if (context->colorDetector[color] == 0)
374
{
375
context->color[v] = color;
376
if (context->highestColorUsed < color)
377
context->highestColorUsed = color;
378
break;
379
}
380
}
381
382
if (context->color[v] < 0)
383
return NOTOK;
384
385
// Run the neighbor list of v and unflag all the colors in use
386
J = gp_GetFirstArc(theGraph, v);
387
while (gp_IsArc(theGraph, J))
388
{
389
w = theGraph->G[J].v;
390
context->colorDetector[context->color[w]] = 0;
391
392
J = gp_GetNextArc(theGraph, J);
393
}
394
395
return OK;
396
}
397
398
/********************************************************************
399
gp_GetNumColorsUsed()
400
********************************************************************/
401
402
int gp_GetNumColorsUsed(graphP theGraph)
403
{
404
ColorVerticesContext *context = (ColorVerticesContext *) gp_GetExtension(theGraph, COLORVERTICES_ID);
405
return context == NULL ? 0 : context->highestColorUsed+1;
406
}
407
408
/********************************************************************
409
gp_ColorVerticesIntegrityCheck()
410
********************************************************************/
411
412
int gp_ColorVerticesIntegrityCheck(graphP theGraph, graphP origGraph)
413
{
414
int I, J, w;
415
ColorVerticesContext *context = (ColorVerticesContext *) gp_GetExtension(theGraph, COLORVERTICES_ID);
416
417
if (theGraph == NULL || origGraph == NULL || context == NULL)
418
return NOTOK;
419
420
if (gp_GetNumColorsUsed(theGraph) <= 0 && theGraph->M > 0)
421
return NOTOK;
422
423
if (_TestSubgraph(theGraph, origGraph) != TRUE)
424
return NOTOK;
425
426
if (_TestSubgraph(origGraph, theGraph) != TRUE)
427
return NOTOK;
428
429
for (I=0; I < theGraph->N; I++)
430
{
431
J = gp_GetFirstArc(theGraph, I);
432
while (gp_IsArc(theGraph, J))
433
{
434
w = theGraph->G[J].v;
435
if (context->color[I] < 0 || context->color[I] == context->color[w])
436
return NOTOK;
437
438
J = gp_GetNextArc(theGraph, J);
439
}
440
}
441
442
return OK;
443
}
444
445