Graph implementation C++

前端 未结 7 739
悲&欢浪女
悲&欢浪女 2020-11-30 17:38

I was wondering about a quick to write implementation of a graph in c++. I need the data structure to be easy to manipulate and use graph algorithms(such as BFS,DFS, Kruskal

7条回答
  •  攒了一身酷
    2020-11-30 18:15

    There can be an even simpler representation assuming that one has to only test graph algorithms not use them(graph) else where. This can be as a map from vertices to their adjacency lists as shown below :-

    #include
    using namespace std;
    
    /* implement the graph as a map from the integer index as a key to the   adjacency list
     * of the graph implemented as a vector being the value of each individual key. The
     * program will be given a matrix of numbers, the first element of each row will
     * represent the head of the adjacency list and the rest of the elements will be the
     * list of that element in the graph.
    */
    
    typedef map > graphType;
    
    int main(){
    
    graphType graph;
    int vertices = 0;
    
    cout << "Please enter the number of vertices in the graph :- " << endl;
    cin >> vertices;
    if(vertices <= 0){
        cout << "The number of vertices in the graph can't be less than or equal to 0." << endl;
        exit(0);
    }
    
    cout << "Please enter the elements of the graph, as an adjacency list, one row after another. " << endl;
    for(int i = 0; i <= vertices; i++){
    
        vector adjList;                    //the vector corresponding to the adjacency list of each vertex
    
        int key = -1, listValue = -1;
        string listString;
        getline(cin, listString);
        if(i != 0){
            istringstream iss(listString);
            iss >> key;
            iss >> listValue;
            if(listValue != -1){
                adjList.push_back(listValue);
                for(; iss >> listValue; ){
                    adjList.push_back(listValue);
                }
                graph.insert(graphType::value_type(key, adjList));
            }
            else
                graph.insert(graphType::value_type(key, adjList));
        }
    }
    
    //print the elements of the graph
    cout << "The graph that you entered :- " << endl;
    for(graphType::const_iterator iterator = graph.begin(); iterator != graph.end(); ++iterator){
        cout << "Key : " << iterator->first << ", values : ";
    
        vector::const_iterator vectBegIter = iterator->second.begin();
        vector::const_iterator vectEndIter = iterator->second.end();
        for(; vectBegIter != vectEndIter; ++vectBegIter){
            cout << *(vectBegIter) << ", ";
        }
        cout << endl;
    }
    }
    

提交回复
热议问题