Data structure and algorithm--C + + implementation of Graph adjacency table notation class

Source: Internet
Author: User

the representation of the graph:


adjacency matrix notation:a simple representation of the preceding graph is the use of a two-dimensional array, called the adjacency matrix notation . if it is a graph, set the two-dimensional array element Arr[u][v] value to True for each edge (U, v), otherwise the array element is false;In the case of a forward graph, for each edge (U, v), set the two-dimensional array element Arr[u][v] value to the weight of that edge, otherwise the array element is set to a large numeric value or to a small array (depending on the context setting);Although the adjacency matrix notation is relatively simple, it requires more space and is suitable for dense types of graphs.


adjacency table notation: Another way to express this is by using adjacency table notation , which is suitable for sparse types of graphs.



In fact, the left array can also be used, if necessary, can be added to save the individual vertices of the information. In general, the linked list of each vertex can be known according to the order of the linked list array on the right.

data structure of nodes in graphs:
Figure node Information typedef struct node{     int edge_num;//boundary number     int src;//source point     int vertex;//itself     

The class interface of the adjacency table notation for graphs:
/********************************************************  class name: adjacency table Diagram **************************************** /class graph{    private:        int edge_num;//The number of vertices of an        int vertex_num;//figure        List<node > * graph_list;//adjacency Table public    :        graph () {}        graph (char* graph[], int edgenum);         ~graph ();        void print ();//print diagram information as adjacency table    private:        vector<int> get_graph_value (char* graph[], int columns);// Get data for each edge        void Addedge (char* graph[], int columns);};

Test function:1, read the data in the diagram file, the data format is as follows:
0,0,1,11,0,2,22,0,3,1
The 1th column is the label of the Edge, the 2nd column is the beginning of the edge, the 3rd column is the end of the edge, and the 4th column is the edge.
/***************************************************************** function Name: read_file* function Description: Read the data information of the graph in the file * parameter list: Buff is the The image information read by the file is saved to the two-dimensional array that the buff points to. * Spec is the maximum number of edges allowed in a file * filename is the diagram file to open * return result: no ************************** /int Read_file (char * * Const buff, const unsigned int spec, const char * const file    Name) {FILE *FP = fopen (filename, "R");        if (fp = = NULL) {printf ("Fail to open file%s,%s.\n", filename, strerror (errno));    return 0;    } printf ("Open file%s ok.\n", filename);    Char Line[max_line_len + 2];    unsigned int cnt = 0;        while (CNT < spec) &&!feof (FP)) {line[0] = 0;        Fgets (line, Max_line_len + 2, FP);        if (line[0] = = 0) continue;        BUFF[CNT] = (char *) malloc (Max_line_len + 2);        strncpy (buff[cnt], line, Max_line_len + 2-1);        BUFF[CNT][4001] = 0;    cnt++;    } fclose (FP); printf ("There is%d lines in file%s.\n", CNT,filename); return CNT;}

2. Release data from the graph in the file you just read
/*****************************************************************   function Name: release_buff*   Function Description: Release data information for the graph in the file you just read *   parameter list: Buff is a graph message pointing to a file read *             Valid_item_num refers to the number of edges in the graph *   return result: void*********************** /void Release_buff (char * * const buff, const int valid_item_num) {for    ( int i = 0; i < Valid_item_num; i++) Free        (Buff[i]);}

3. Main test function
int main (int argc, char *argv[]) {    char *topo[5000];    int edge_num;    char *demand;    int demand_num;    Char *topo_file = argv[1];    Edge_num = Read_file (topo, topo_file);    if (Edge_num = = 0)    {        printf ("Please input valid topo file.\n");        return-1;    }    Graph G (topo, edge_num);//Create a Graph object G    g.print ();//Print the graph information in the form of an adjacency table    release_buff (topo, edge_num); return 0;}

The source code of the Adjacency table notation class for the graph:
#ifndef graph_h#define graph_h#include <list> #include <iostream> #include <vector> #include < stdlib.h> #include <string.h> #include <algorithm> #include <iterator> #include <stdio.h># Include <errno.h> #include <unistd.h> #include <signal.h>using namespace std; #define Max_vertex_num 600//Graph node Information typedef struct node{int edge_num;//boundary number int src;//source point int vertex;//self int weight;//edge weight}node; /******************************************************** class Name: adjacency table Diagram *********************************************  /class graph{Private:int edge_num;//the number of edges of the graph int vertex_num;//the vertices of the graph list<node> *         graph_list;//adjacency Table Public:graph () {} Graph (char* graph[], int edgenum);        ~graph ();        void print ();//Print the graph information in the form of an adjacency table private:vector<int> get_graph_value (char* graph[], int columns);//Get data for each edge void Addedge (char* graph[], int columns);};/ *********************Function Name: Print function Description: Outputs the information of the graph to the standard output parameter list as an adjacency table: No return result: no ************************************* /void Graph::p rint () {cout << *****************************************************************     * "<< Endl;  for (int i = 0, i < max_vertex_num; ++i) {for (int i = 0; i < Vertex_num; ++i) {if (Graph_list[i].begin ()            ! = Graph_list[i].end ()) {cout << i << "--"; for (List<node>::iterator it = Graph_list[i].begin (); It! = Graph_list[i].end (); ++it) {cout <<            (*it). Vertex << "(Side number:" << (*it). Edge_num << ", Weight:" << (*it). Weight << ")--";        } cout << "NULL" << Endl; }} cout << "******************************************************************" << Endl; }/************************************************* function Name: Get_graph_value function Description: Saves the information for each edge of the diagram to an array of argument lists: Graph: A two-dimensional array pointing to graph information columns: the firstSeveral sides return results: No *************************************************/vector<int> graph::get_graph_value (char* graph[    ], int columns) {vector<int> v;    Char buff[20];    int i = 0, j = 0, Val;    memset (Buff, 0, 20);            while ((graph[columns][i]! = ' \ n ') && (graph[columns][i]! = ') ') {if (graph[columns][i]! = ', ') {            BUFF[J] = Graph[columns][i];        j + +;            } else{j = 0;             val = atoi (buff);            V.push_back (Val);        memset (Buff, 0, 20);    } i++;     } val = atoi (buff);    V.push_back (Val); return v;}          /************************************************* function Name: Addedge function Description: Add information for each edge of the graph to the parameter list in the adjacency table of the graph: graph: A two-dimensional array pointing to the graph information Columns: The first side of the graph returns the result: No *************************************************/void Graph::addedge (char* graph[], int    Columns) {node node;    Vector<int> v = get_graph_value (graph, columns);    Node.edge_num = v[0];    NODE.SRC = v[1];    Node.vertex = v[2]; Node.weight = v[3];    if (Node.vertex > Vertex_num) vertex_num = Node.vertex; To consider duplicate edges, but the weights of the edges are different for (list<node>::iterator it = Graph_list[node.src].begin (); It! = Graph_list[node.src].end ( );  ++it) {if ((*it). Vertex = = Node.vertex) {if ((*it). Weight > Node.weight) {(*it). Weight =               Node.weight;        } return; }} graph_list[node.src].push_back (node);}          /************************************************* function Name: constructor function Description: Save the information of the diagram as an adjacency table and save the list of vertex parameters that must pass: graph: A two-dimensional array pointing to the graph information    Edgenum: The number of sides of the graph returns the result: No *************************************************/graph::graph (char* graph[], int edgenum) {     Edge_num = Edgenum;    Vertex_num = 0;    Graph_list = new list<node>[max_vertex_num+1];       for (int i = 0; i < Edgenum; ++i) {Addedge (graph, I); } vertex_num++;} /************************************************* function Name: destructor function Description: Release the dynamically allocated memory parameter list: No results returned: no **************************    /graph::~graph () {Delete[] graph_list;} #endif

to test the source code of the function:
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include < time.h> #include <sys/timeb.h> #include <errno.h> #include <unistd.h> #include <signal.h># Include <stdio.h> #include "graph.h" #define Max_line_len 4000int read_file (char * * Const buff, const unsigned int spe C, const char * const filename), void Release_buff (char * * const buff, const int valid_item_num); int main (int argc, char *a    Rgv[]) {char *topo[5000];    int edge_num;    Char *demand;    int demand_num;    Char *topo_file = argv[1];    Edge_num = Read_file (topo, topo_file);        if (Edge_num = = 0) {printf ("Please input valid topo file.\n");    return-1; } graph G (topo, edge_num);//Create a Graph Object G g.print ();//Print the graph information in the form of an adjacency table Release_buff (topo, edge_num); return 0;} /***************************************************************** function Name: read_file* function Description: Read the data information of the graph in the file * parameter list: Buff is the File read diagram information saved to a two-dimensional array of buff points * Specis the maximum number of edges allowed in the file * filename is the diagram file to open * return result: no *****************************************************************/in     T Read_file (char * * Const buff, const unsigned int spec, const char * const filename) {File *FP = fopen (filename, "R");        if (fp = = NULL) {printf ("Fail to open file%s,%s.\n", filename, strerror (errno));    return 0;    } printf ("Open file%s ok.\n", filename);    Char Line[max_line_len + 2];    unsigned int cnt = 0;        while (CNT < spec) &&!feof (FP)) {line[0] = 0;        Fgets (line, Max_line_len + 2, FP);        if (line[0] = = 0) continue;        BUFF[CNT] = (char *) malloc (Max_line_len + 2);        strncpy (buff[cnt], line, Max_line_len + 2-1);        BUFF[CNT][4001] = 0;    cnt++;    } fclose (FP);    printf ("There is%d lines in file%s.\n", CNT, filename); return CNT;}   /***************************************************************** function Name: release_buff* function Description: Release data information for the graph in the file you just read * Parameter list: Buff is a its that points to a file read* Valid_item_num refers to the number of edges in the graph * return result: void*****************************************************************/void R Elease_buff (char * * const buff, const int valid_item_num) {for (int i = 0; i < valid_item_num; i++) Free (buff [i]);}

Test Case 0:
0,0,1,11,0,2,22,0,3,13,2,1,34,3,1,15,2,3,16,3,2,17,3,0,1

test Case 1:
0,0,13,151,0,8,172,0,19,13,0,4,84,1,0,45,2,9,196,2,15,87,3,0,148,3,11,129,4,1,1510,4,5,1711,5,8,1812,5,9,1413,5,6,214,6,1 7,415,7,13,116,7,16,1917,8,6,118,8,12,1719,9,14,1120,10,12,121,11,7,1222,11,4,723,12,14,524,13,17,1225,13,4,226,14,19,927 , 15,10,1428,15,18,229,16,8,130,17,9,1431,17,19,332,17,18,1033,18,15,834,18,3,835,19,18,1236,2,3,2037,3,5,2038,5,7,2039,7 , 11,2040,11,13,2041,17,11,2042,11,19,2043,17,5,2044,5,19,20

Operation Result:
[email protected]_ever:~/linux_ever/algorithm/graph_ch9# lscase0 case1 graph.h testgraph testgraph.cpp[email& nbsp;protected]_ever:~/linux_ever/algorithm/graph_ch9#./testgraph./case0/topo.csv Open file./case0/topo.csv OK. There is 8 lines in file ./case0/topo.csv.******************************************************************0--> 1 (Side number: 0, Weight: 1)-->2 (Edge number: 1, Weight: 2)-->3 (side number: 2, Weight: 1)-->null2-->1 (side number: 3, Weight: 3)-->3 (side number: 5, Weight: 1)-->null3-- >1 (Side number: 4, Weight: 1)-->2 (Edge number: 6, Weight: 1)-->0 (side number: 7, Weight: 1)-->null************************************************ [email protected]_ever:~/linux_ever/algorithm/graph_ch9#./testgraph./case1/topo.csv Open File./case1/topo.csv OK. There is lines in file./case1/topo.csv.******************************************************************0-- >13 (Side number: 0, Weight:)-->8 (Edge number: 1, Weight: +)-->19 (Edge number: 2, Weight: 1)-->4 (side number: 3, Weight: 8)-->null1-->0 (side number: 4, Weight: 4)- Null2-->9 (Side number: 5, Weight: +)-->15 (Edge number: 6, Weight: 8)-->3 (Edge number: 36, Weight:)-->nulL3-->0 (Side number: 7, Weight:)-->11 (side number: 8, Weight:)-->5 (Edge number: 37, Weight:)-->null4-->1 (Edge number: 9, Weight:)-->5 (side number: 10, Weight: 17 )-->null5-->8 (Edge number: 11, Weight:)-->9 (side number: 12, Weight: +)-->6 (Edge number: 13, Weight: 2)-->7 (side number: 38, Weight: 44)-->19 (Edge number: +, weight :-->null6-->17 (Side number: 14, Weight: 4)-->null7-->13 (Edge number: 15, Weight: 1)-->16 (side number: 16, Weight: +)-->11 (side number: 39, Weight: 20)-- >null8-->6 (Side number: 17, Weight: 1)-->12 (Edge number: 18, Weight: +)-->null9-->14 (Edge number: 19, Weight: one)-->null10-->12 (side number: 20, weight : 1)-->null11-->7 (side number: 21, Weight:-->4) (Edge number: 22, Weight: 7)-->13 (side number: 40, Weight:)-->19 (side number: 42, Weight:)-->null12-- &GT;14 (side number: 23, Weight: 5)-->null13-->17 (Edge number: 24, Weight:)-->4 (Edge number: 25, Weight: 2)-->null14-->19 (side number: 26, Weight: 9)- NULL15--&GT;10 (Side number: 27, Weight: +)-->18 (side number: 28, Weight: 2)-->null16-->8 (Edge number: 29, Weight: 1)-->null17-->9 (side number: 30, Weight: 14) --&GT;19 (Side number: 31, Weight: 3)-->18 (Edge number: 32, Weight: Ten)-->11 (Edge number: 41, Weight:)-->5 (side number: 43, Weight:)-->null18-->15 (side number: 33, Weight: 8)-->3 (Edge number: 34, Weight: 8)-->null19-->18 (Edge number: 35, Weight:)-->null******************************************* *********************** 


The first column of each row of the output shows the labels for each vertex. For example:0-->13 (Side number: 0, Weight:)-->8 (Edge number: 1, Weight:)-->19 (Edge number: 2, Weight: 1)-->4 (side number: 3, Weight: 8)-->null

above, the edges of vertices 0 to 13 have a side number of 0 and a weight of 15. Vertex 0 to Vertex 8 has a side number of 1 and a weight of 17. Vertex 0 to Vertex 19 has a side number of 2 and a weight of 1. Vertex 0 to Vertex 4 has a side number of 3 and a weight of 8.

Data structure and algorithm--C + + implementation of Graph adjacency table notation class

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.