jeudi 28 juillet 2016

How to randomly pick a vertices from graph?

I am looking for solution to pick a number randomly from graph using c++.
For example I have a graph that add edge (one or more) between two vertices, how can I pick a number randomly?
some of code :

#include <iostream>
#include <list>
#include <queue>

using namespace std;
// Graph class represents a undirected graph using adjacency list representation
class Graph
{
private:
    int V; // # of vertices
    list<int> *adj;  // Pointer to an array containing adjacency lists
public:
    Graph(int V)  // Constructor
    {
        this->V = V;
        adj = new list<int>[V];
    }
    void addEdge(int v, int w); // function to add an edge to graph
    void print(int v, int w); //function to display 
    };

void Graph::addEdge(int v, int w)
{
    adj[v].push_front(w); // Add w to v’s list.
    adj[w].push_front(v); // Add v to w’s list.
    print(v, w);

}

void Graph::print(int v, int w) {
cout << v << " - " << w << endl;}


In the main:

Graph g(4);
    g.addEdge(0, 1);
    g.addEdge(0, 2);
    g.addEdge(1, 3);


Sample output:

0 - 1
0 - 2
1 - 3




Aucun commentaire:

Enregistrer un commentaire