c++ - BFS Segmentation Fault -
#include <iostream> #include <sstream> #include <fstream> #include <cstdlib> #include <list> // #include "bst.h" using namespace std; class graph { int v; // number of vertices list<int> *adj; // pointer array of adjacency list public: graph(int v); // constructor void addedge(int v, int w); // function add edge graph void bfs(int s); // prints breadth first search graph s. }; //defining constructor graph::graph(int v) { this->v = v; adj = new list<int>[v]; } // function add edges vertice. void graph::addedge(int v, int w) { adj[v].push_back(w); // adding w v's list } // function print out breadth first search given graph starting @ s. void graph::bfs(int s) { bool *visited = new bool[v]; cout << "value of v: " << v << endl; for(int = 0; < v; i++) visited[i] = false; // create queue bfs list<int> queue; //marking starting node visited , adding queue. visited[s] = true; queue.push_back(s); // iterator iterate on adjacent list vertices list<int>::iterator i; while(!queue.empty()) { // printing current vertex , removing queue s = queue.front(); cout << s << " "; queue.pop_front(); // going through adjacency list , adding queue if has not been visited. (i = adj[s].begin(); != adj[s].end(); i++) { if(!visited[*i] ) { visited[*i] = true; queue.push_back(*i); } } } } int main(int argc, char* argv[]) { // if user didn't provide filename command line argument, // print error , exit. if (argc != 3) { cout << "usage: " << argv[0] << " <filename> <starting node index>" << endl; exit(1); } string line; int size; int starting_vertice; char colon; int vertex; ifstream myfile (argv[1]); if (myfile.is_open()) { getline(myfile, line); istringstream iss(line); iss >> size; // initializing graph of size taken in. graph g(size); cout << "vertex: " << "connected vertices" << endl; (int = 0; < size; i++) { getline(myfile, line); istringstream iss(line); iss >> starting_vertice; iss >> colon; while (iss >> vertex) { g.addedge(starting_vertice, vertex); } cout << endl; } myfile.close(); cout << "breadth first search starting @ vertex " << argv[2] << " : " << endl; // cout << atoi(argv[2]) << endl; g.bfs( atoi(argv[2]) ); } else cout << "unable open file" << endl; return 0; }
this code implement breadth first search specific input file. input file follows:
4 1:2 3 4 2:4 3:4 4:
i know i'm getting segmentation fault while looping through adjacency list last vertex can't, life of me, figure out how fix this. help?
edit: also, starting node index gave 1.
welcome off-by-one club. arrays zero-indexed. in graph
, create list of size v
, then, through graph::addedge
, go on access v
-th element of v
-sized array adj
. fix this, have 2 choices - number vertices 0
v-1
, or increase size of adj
v+1
. latter:
graph::graph(int v) { this->v = v; adj = new list<int>[v+1]; vvvvvv }
Comments
Post a Comment