Algorithms_in_C 1.0.0
Set of algorithms implemented in C.
|
Prim's algorithm implementation in C to find the MST of a weighted, connected graph. More...
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <inttypes.h>
Macros | |
#define | MAX 20 |
for IO operations More... | |
#define | INF 999 |
Functions | |
uint16_t | minimum (uint16_t arr[], uint16_t N) |
Finds index of minimum element in edge list for an arbitrary vertex. More... | |
void | prim (uint16_t G[][MAX], uint16_t MST[][MAX], uint16_t V) |
Used to find MST of user-generated adj matrix G. More... | |
static void | test (uint16_t G[][MAX], uint16_t MST[][MAX], uint16_t V) |
Self-test implementations. More... | |
void | user_graph (uint16_t G[][MAX], uint16_t MST[][MAX], uint16_t V) |
Function user_graph(); gets user input adj. More... | |
int | main (int argc, char const *argv[]) |
Main function. More... | |
Prim's algorithm implementation in C to find the MST of a weighted, connected graph.
Prim's algorithm uses a greedy approach to generate the MST of a weighted connected graph. The algorithm begins at an arbitrary vertex v, and selects a next vertex u, where v and u are connected by a weighted edge whose weight is the minimum of all edges connected to v. @references Page 319 "Introduction to the Design and Analysis of Algorithms" - Anany Levitin
To test - run './prim -test' prim() will find the MST of the following adj. matrix:
0 1 2 3 1 0 4 6 2 4 0 5 3 6 5 0
The minimum spanning tree for the above weighted connected graph is given by the following adj matrix:
0 1 2 3 1 0 0 0 2 0 0 0 3 0 0 0
The following link provides a visual representation of graphs that can be used to test/verify the algorithm for different adj matrices and their weighted, connected graphs.
#define MAX 20 |
for IO operations
for string comparison for assert() for uint16_t
int main | ( | int | argc, |
char const * | argv[] | ||
) |
Main function.
argc | commandline argument count (ignored) |
argv | commandline array of arguments (ignored) |
< weighted, connected graph G
< adj matrix to hold minimum spanning tree of G
< number of vertices in V in G
uint16_t minimum | ( | uint16_t | arr[], |
uint16_t | N | ||
) |
Finds index of minimum element in edge list for an arbitrary vertex.
arr | graph row |
N | number of elements in arr |
void prim | ( | uint16_t | G[][MAX], |
uint16_t | MST[][MAX], | ||
uint16_t | V | ||
) |
Used to find MST of user-generated adj matrix G.
|
static |
Self-test implementations.
void user_graph | ( | uint16_t | G[][MAX], |
uint16_t | MST[][MAX], | ||
uint16_t | V | ||
) |
Function user_graph(); gets user input adj.
matrix and finds MST of that graph