opm-simulators/dfs.c

107 lines
2.4 KiB
C
Raw Normal View History

/*======================================================================
File: dfs.c
Created: Tue May 6 09:27:26 2008
Author: Jostein R. Natvig <Jostein.R.Natvig@sintef.no>
Revision: $Id$
====================================================================*/
#include <assert.h>
2010-08-19 05:52:10 -05:00
/*
* Assign color (nonnegative number) to each connected component of graph
*/
void dfs (int size, int *ia, int *ja, int *ncolors, int *color, int* work)
{
2010-08-19 06:02:50 -05:00
int i, c;
2010-08-20 09:18:22 -05:00
enum {UNVISITED = -1, VISITED = -2};
2010-08-19 06:02:50 -05:00
int *stack = work;
2010-08-20 09:18:22 -05:00
int *count = work + size;
2010-08-19 06:02:50 -05:00
int *bottom = stack;
2010-08-19 06:02:50 -05:00
*ncolors = 0; /* colors are nonnegative */
2010-08-19 06:02:50 -05:00
for (i=0; i<size; ++i) {
2010-08-20 09:18:22 -05:00
color [i] = UNVISITED;
count [i] = ia[i+1]-ia[i];
2010-08-19 06:02:50 -05:00
}
2010-08-19 06:02:50 -05:00
/* Push seeds on stack */
for (i=0; i<size; ++i) {
2010-08-20 09:18:22 -05:00
if(color[i] >= 0) { /* FINISHED */
2010-08-19 06:02:50 -05:00
continue;
}
2010-08-19 06:02:50 -05:00
*stack++ = i; /* push i */
2010-08-20 09:18:22 -05:00
color[i] = VISITED;
2010-08-19 06:02:50 -05:00
while ( stack != bottom ) {
c = *(stack-1); /* peek */
2010-08-20 09:18:22 -05:00
if (count[c] > 0){
int child = ja[ia[c] + count[c]-1];
count[c]--;
if (color[child] == UNVISITED) {
*stack++ = child;
color[c] = VISITED;
}
2010-08-19 06:02:50 -05:00
} else {
color[c] = *ncolors;
--stack; /* pop c */
}
}
++*ncolors;
}
}
#if TEST
#include <stdlib.h>
#include <stdio.h>
/* Test code. Reads a sparse matrix from a file specified on the */
/* command line with file format "m n\n i1 j1 v1\n i2 j2 v2\n ...". */
/* Computes reorder sequence */
int main (int argc, char *argv [])
{
2010-08-19 06:02:50 -05:00
int *color, *work;
int j, ncolors;
2010-08-20 09:18:22 -05:00
#if 0
2010-08-19 06:02:50 -05:00
int size = 8;
int ia[] = {0, 1, 2, 4, 5, 5, 7, 7, 8};
int ja[] = {1, 2, 0, 3, 4, 5, 6, 6};
2010-08-20 09:18:22 -05:00
#else
int size = 3;
int ia[] = {0,2,5,7};
int ja[] = {0,1,1,0,2,2,1};
#endif
2010-08-19 06:02:50 -05:00
color = malloc (size * sizeof *color);
2010-08-20 09:18:22 -05:00
work = malloc (2*size * sizeof *work);
2010-08-19 06:02:50 -05:00
dfs(size, ia, ja, &ncolors, color, work);
2010-08-19 06:02:50 -05:00
fprintf(stderr, "ncolors = %d\n", ncolors);
for (j=0; j<size; ++j) {
fprintf(stderr, "%d\n", color[j]);
}
2010-08-19 06:02:50 -05:00
free (color);
free (work);
return 0;
}
#endif
2010-08-19 06:02:50 -05:00
/* Local Variables: */
/* c-basic-offset:4 */
/* End: */