Skip to content

Instantly share code, notes, and snippets.

@Roo4L
Created May 16, 2020 16:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Roo4L/b5ad2ab8426ff9fe43b490f1525b90ff to your computer and use it in GitHub Desktop.
Save Roo4L/b5ad2ab8426ff9fe43b490f1525b90ff to your computer and use it in GitHub Desktop.
graphviz drawing
#include <graphviz/cgraph.h>
#include <graphviz/gvc.h>
#include <stdio.h>
#include <stdlib.h>
#include "main.h"
#define P_LEN 15
#define max(a,b) \
({ __typeof__ (a) _a = (a); \
__typeof__ (b) _b = (b); \
_a > _b ? _a : _b; })
void add_node(node *n, Agnode_t **agn, Agraph_t *g);
void draw_list(Agraph_t *g, Agnode_t **agn, node *n, int k);
void draw_graph(TREE *tree) {
Agraph_t *g;
GVC_t* gvc;
gvc = gvContext();
g = agopen("G", Agstrictundirected, NULL);
Agsym_t *atr;
atr = agattr(g, AGNODE, "shape", "circle");
Agnode_t *agn[3];
if (tree->root == NULL) {
printf("Tree is empty\n");
return;
}
if (tree->root->left != NULL) {
char s[P_LEN];
sprintf(s, "x=%d", tree->root->boundary);
agn[0] = agnode(g, s, TRUE);
}
else {
draw_list(g, agn, tree->root, 0);
}
add_node(tree->root, agn, g);
gvLayout(gvc, g, "dot");
gvRenderFilename(gvc, g, "png", "out.png");
gvFreeLayout(gvc, g);
agclose(g);
}
void add_node(node *n, Agnode_t **agn, Agraph_t *g) {
if (n->left == NULL) {
return;
}
char s[P_LEN];
if (n->left->left != NULL) {
if (n->axis == 0) {
sprintf(s, "y=%d", n->left->boundary);
}
else {
sprintf(s, "x=%d", n->left->boundary);
}
agn[1] = agnode(g, s, TRUE);
}
else {
draw_list(g, agn, n->left, 1);
}
if (n->right->left != NULL) {
if (n->axis == 0) {
sprintf(s, "y=%d", n->right->boundary);
}
else {
sprintf(s, "x=%d", n->right->boundary);
}
agn[2] = agnode(g, s, TRUE);
}
else {
draw_list(g, agn, n->right, 2);
}
Agedge_t *e;
e = agedge(g, agn[0], agn[1], NULL, TRUE);
e = agedge(g, agn[0], agn[2], NULL, TRUE);
Agnode_t *right = agn[2];
agn[0] = agn[1];
add_node(n->left, agn, g);
agn[0] = right;
add_node(n->right, agn, g);
}
void draw_list(Agraph_t *g, Agnode_t **agn, node *n, int k) {
char *s;
int len = 0;
con_list *elem;
elem = n->content;
while (elem != NULL) {
elem = elem->next;
len++;
}
agn[k] = agnode(g, NULL, TRUE);
if (len != 0) {
//create node name
char f[P_LEN];
s = (char *)malloc(sizeof(char) * P_LEN * len);
memset(s, 0x00, 1);
elem = n->content;
sprintf(f, "{ (%d,%d)", elem->data->key[0], elem->data->key[1]);
strcat(s, f);
for (int i = 1; i < len; i++) {
elem = elem->next;
sprintf(f, "| (%d,%d)", elem->data->key[0], elem->data->key[1]);
strcat(s, f);
}
strcpy(f, "}");
strcat(s, f);
agset(agn[k], "label", s);
free(s);
}
agset(agn[k], "shape", "Mrecord");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment