CS 3343/3341 Analysis of Algorithms Spring 2012 |
Recitation 9 Graph of Capitals, C Version |
| Graph construction: 48 mainland US capitals. |
|---|
// graph.c: set up data structure for graph
// Uses adjacency list representation
#include <stdio.h>
#include <stdlib.h>
#define GRAPHSIZE 48
struct graphnode { // node for graph's vertex
struct edgenode* firstedgenode; // to entire adj. list
// other vertex info here
};
struct edgenode { // holds graph's edge info
int vertexnum; // head end of edge
int edgedist; // data: here it's distance
struct edgenode* nextedgenode; // next edge
// other edge info here
};
void printgraph(struct graphnode* graph[], int count);
struct graphnode* newgraphnode();
struct edgenode* newedgenode(int num, struct edgenode* node, int dist);
void insert(struct graphnode* graph[], int num1, int num2, int dist);
int edgedistance(struct graphnode* graph[], int v1, int v2);
int pathlength(struct graphnode* graph[], int path[], int len);
int main() {
// three Hamiltonian paths
int ham1[] =
{47,45,42,44,46,43,41,40,39,37,33,38,
34,28,29,24,21,16,10,15,20,23,27,32,
26,36,35,31,30,25,22,18,17,11, 7,12,
8,13,19,14, 9, 5, 4, 0, 2, 1, 6, 3};
int ham2[] =
{47,45,42,44,46,43,41,40,38,39,37,32,
36,35,31,30,25,22,17,11,12,18,26,27,
33,34,29,28,23,19,13,14,20,24,21,15,
16,10, 6, 5, 9, 8, 7, 4, 1, 0, 2, 3};
int ham3[] =
{47,45,42,44,46,43,41,40,39,37,33,32,
36,35,31,30,25,26,27,28,23,20,19,18,
22,17,11,12,13,14,15, 9, 8, 7, 4, 5,
1, 0, 2, 3, 6,10,16,21,24,29,34,38};
struct graphnode* graph[GRAPHSIZE];
int i;
int num1, num2, num;
for(i = 0; i < GRAPHSIZE; i++) graph[i] = newgraphnode();
FILE *infile;
infile = fopen("capsdist.txt", "r");
if (infile == NULL) {
fprintf(stderr, "Can't open %s\n", "source.txt");
exit(1);
}
while (fscanf(infile, "%i%i%i", &num1,&num2,&num) != EOF) {
// carry out insertions, both directions
insert(graph, num1, num2, num);
insert(graph, num2, num1, num);
}
printgraph(graph, GRAPHSIZE);
printf("Path length: %i\n", pathlength(graph, ham3, 48));
}
struct graphnode* newgraphnode(){
// may want to use this to create graphnodes
}
struct edgenode* newedgenode(int num, struct edgenode* node,
int dist) {
// may want to use this to create edgenodes
}
void insert(struct graphnode* graph[], int num1, int num2, int dist){
// patch the new node in at the start
if (graph[num1] -> firstedgenode == NULL) {
// create new adjacency list, with
// a node for num2, its only entry
}
else {
// patch in a node for num2 at the
// start of the existing adj list
}
}
void printgraph(struct graphnode* graph[], int count) {
// print the data in the graph,
// perhaps in the form below
}
int edgedistance(int v1, int v2) {
// if (v1, v2) is an edge
// return edgeDist of this edge
// otherwise return -1
}
int pathlength(struct graphnode* graph[], int path[], int len) {
// calculate and return the length
// of the path specified by the input
// parameter. If the "path" includes
// a non-edge return -1
}
|