graph_t* MatrixToGraph(double *adjac_mtx_ptr, int iGraphOrder) { int i, j, idx; graph_t *ptrGraph; /* Initialize the graph that we want to return. */ ptrGraph = graph_new(iGraphOrder); /* Loop through the adjacency matrix to create the graph. We assume * that the adjacency matrix is symmetric and only consider the super- * diagonals of the matrix. */ /* The indexing here seems flipped, but it's due to the translation * between MATLAB and C element ordering. */ for (j = 0; j < iGraphOrder; j++) for (i = j + 1; i < iGraphOrder; i++) { /* The matrix adj_mtx is stored as a 1-dimensional array, so * we must convert the coordinate (i, j) to the corresponding * 1-dimensional index. */ idx = j + i * iGraphOrder; /* If the entry of the adjacency matrix is a 1, we want to add * an edge to our graph. */ if(adjac_mtx_ptr[idx] == 1) GRAPH_ADD_EDGE(ptrGraph, i, j); } /* Just to be cautios, ensure that we've produced a valid graph. */ ASSERT(graph_test(ptrGraph, NULL)); return ptrGraph; }
boolean graph_write_dimacs_binary(graph_t *g, char *comment,FILE *fp) { char *buf; char *header=NULL; int headersize=0; int headerlength=0; int i,j; ASSERT((sizeof(setelement)*8)==ELEMENTSIZE); ASSERT(graph_test(g,NULL)); ASSERT(fp!=NULL); buf=malloc(MAX(1024,g->n/8+1)); header=malloc(1024); header[0]=0; headersize=1024; if (comment) { strcpy(buf,"c "); strncat(buf,comment,1000); strcat(buf,"\n"); STR_APPEND(buf); } sprintf(buf,"p edge %d %d\n",g->n,graph_edge_count(g)); STR_APPEND(buf); for (i=0; i < g->n; i++) { if (g->weights[i]!=1) { sprintf(buf,"n %d %d\n",i+1,g->weights[i]); STR_APPEND(buf); } } fprintf(fp,"%d\n",(int)strlen(header)); fprintf(fp,"%s",header); free(header); for (i=0; i < g->n; i++) { memset(buf,0,i/8+1); for (j=0; j<i; j++) { if (GRAPH_IS_EDGE_FAST(g,i,j)) { buf[j/8] |= SET_BIT_MASK(7-j%8); } } fwrite(buf,1,i/8+1,fp); } free(buf); return TRUE; }
/* * graph_write_dimacs_ascii() * * Writes an ASCII dimacs-format file of graph g, with comment, to the * file stream fp. * * Returns TRUE if successful, FALSE if an error occurred. */ boolean graph_write_dimacs_ascii(graph_t *g, char *comment, FILE *fp) { int i,j; ASSERT((sizeof(setelement)*8)==ELEMENTSIZE); ASSERT(graph_test(g,NULL)); ASSERT(fp!=NULL); if (comment) fprintf(fp,"c %s\n",comment); fprintf(fp,"p edge %d %d\n",g->n,graph_edge_count(g)); for (i=0; i < g->n; i++) if (g->weights[i]!=1) fprintf(fp,"n %d %d\n",i+1,g->weights[i]); for (i=0; i < g->n; i++) for (j=0; j<i; j++) if (GRAPH_IS_EDGE_FAST(g,i,j)) fprintf(fp,"e %d %d\n",i+1,j+1); return TRUE; }
int main(int argc, char *argv[]) { graph_t *g; set_t s; if (argc!=2) { fprintf(stderr,"%s <dimacs_file>\n",argv[0]); return 1; } g=graph_read_dimacs_file(argv[1]); if (g==NULL) return 1; ASSERT(graph_test(g,stderr)); s=clique_find_single(g,0,0,FALSE,NULL); set_print(s); return 0; }