#include "graph1.h" #include "cstdlib" graph::graph(){ // Nothing needs to be done except set the number of nodes to zero myNumberNodes = 0; } void graph::operator +=(const node & x){ // If the vector of nodes is full, resize it and resize the adjacency // matrix. We'll make sure thet the length of the node vector always // equals the dimensions of the adjacency matrix if(myNumberNodes == myNodes.length()){ myNodes.resize(2*myNumberNodes+1); myMatrix.resize(2*myNumberNodes+1); for(int i = 0; i <= 2*myNumberNodes; i++) myMatrix[i].resize(2*myNumberNodes+1); } // Insert the new node at the end myNodes[myNumberNodes] = x; // Since the new node has no neighbors to start with, set the // corresponding row and column to false for(int i = 0; i <= myNumberNodes; i++){ myMatrix[myNumberNodes][i] = false; myMatrix[i][myNumberNodes] = false; } myNumberNodes++; } void graph::operator +=(const edge & x){ // Get the indices of the two endpoints of the edge in the vector of // nodes int i = getIndex(x.getNode1()); int j = getIndex(x.getNode2()); // Use these indices to turn on the corresponding elements in the // adjacency matrix myMatrix[i][j] = myMatrix[j][i] = true; } apvector graph::get_neighbors(const node & x){ // Get the index of the node int i = getIndex(x); // Set up a vector for the list of neighbors apvector neighbors; // Scan the row corresponding to the node x in the adjacency matrix // and pick up neighboring nodes for(int j = 0; j < myNumberNodes; j++) if(myMatrix[i][j]) neighbors.push_back(myNodes[j]); return neighbors; } int graph::getIndex(const node & x){ for(int i = 0; i < myNumberNodes; i++) if(x == myNodes[i]) return i; return -1; }