c++ directed graph depth first search -
i attempting write method dfs method directed graph. right running segmentation fault, , unsure is. understand of directed graphs believe logic right... fresh set of eyes nice help.
here function:
void wdigraph::depth_first (int v) const { static int fvertex = -1; static bool* visited = null; if( fvertex == -1 ) { fvertex = v; visited = new bool[size]; for( int x = 0; x < size; x++ ) { visited[x] = false; } } cout << label[v]; visited[v] = true; (int v = 0; v < adj_matrix.size(); v++) { for( int x = 0; x < adj_matrix.size(); x++) { if( adj_matrix[v][x] != 0 && visited[x] != false ) { cout << " -> "; depth_first(x); } if ( v == fvertex ) { fvertex = -1; delete [] visited; visited = null; } } } }
class definition:
class wdigraph { public: wdigraph(int =no_nodes); // default constructor ~wdigraph() {}; // destructor int get_size() { return size; } // returns size of digraph void depth_first(int) const;// traverses graph using depth-first search void print_graph() const; // prints adjacency matrix of digraph private: int size; // size of digraph vector<char> label; // node labels vector< vector<int> > adj_matrix; // adjacency matrix };
thanks!
there few things might want consider. first function level static variables not idea, can redesign , make either regular variables (at cost of allocations) or instance members , keep them alive.
the function assumes adjacency matrix square, initialization code not shown, should checked. assumption can removed making inner loop condition adj_matrix[v].size()
(given node v
) or else if invariant, add assert before inner loop: assert( adj_matrix[v].size() == adj_matrix.size() && "adj_matrix not square!" );
--the same goes member size
, size of adj_matrix
self.
the whole algorithm seems more complex should, dfs starting @ node v has general shape of:
dfs( v ) set visited[ v ] operate on node (print node label...) each node reachable v: if not visited[ node ]: dfs( node )
your algorithm seems (incorrectly way) transversing graph in opposite direction. set given node visited
, , try locate node start point of edge node. is, instead of following nodes reachable v
, trying nodes v
reachable. if case (i.e. if objective printing paths converge in v
) must careful not hit same edge twice or end in infinite loop -> stackoverflow.
to see end stackoverlow, consider example. start node 1
. create visited
vector , mark position 1
visited. find there edge (0,1) in tree, , triggers if: adj_matrix[0][1] != 0 && visited[1]
, enter recursively start node being 1
again. time don't construct auxiliary data, remark visited[1]
, enter loop, find same edge , call recursively...
Comments
Post a Comment