Recursive Depth First Search (DFS) algorithm in C++ -
i've implemented graph in class graph
adjacency matrix required functions access , modify it, ones needed in dfs algorithm
// graph x, node v string x.get_node_value(v) //returns the label of node queue x.neighbors(v) //returns queue adjacent nodes node v (nodes index on graph starts 1)
now tried implement recursive dfs stuck @ point, never recurse after calls again, works , finds goal if exists on path before reaches leaf node, stops after reaching leaf node
it keeps track of nodes indicating colors, unvisited node white, node in progress grey, node done (visited , children visited) black.
here's kickoff function:
int search::dfsr(const std::string search_key, graph& x, int starting_node){ color * visited_nodes = new color[x.size()]; for(int i=0; i<x.size(); i++){visited_nodes[i] = white;} bool goal_f = 0; int goal = dfsutil(search_key, x, starting_node, visited_nodes, goal_f); if(goal_f) return goal; else return -1; }
and here's visit function:
int search::dfsutil(std::string search_key, graph& x, int current_node, color(visited_nodes)[], bool& goal_f){ visited_nodes[current_node-1] = grey; //-1 because array index start 0 nodes index on graph starts 1 if(x.get_node_value(current_node) == search_key ){ goal_f = 1; return current_node; } else{ std::queue <int> childs = x.neighbors(current_node); while(!childs.empty() && !goal_f){ if(visited_nodes[childs.front()-1] == white){ return dfsutil(search_key, x, childs.front(), visited_nodes, goal_f); } childs.pop(); } visited_nodes[current_node-1] = black; } }
tested on graph:
it finds goal if within a, b, or d, otherwise exits without errors
the following change code should help:
int search::dfsutil(std::string search_key, graph& x, int current_node, color(visited_nodes)[], bool& goal_f){ visited_nodes[current_node-1] = grey; //-1 because array index start 0 nodes index on graph starts 1 if(x.get_node_value(current_node) == search_key ){ goal_f = 1; return current_node; } else{ std::queue <int> childs = x.neighbors(current_node); while(!childs.empty() && !goal_f){ if(visited_nodes[childs.front()-1] == white){ int result = dfsutil(search_key, x, childs.front(), visited_nodes, goal_f); if( result >= 0 ) { return result; } } childs.pop(); } visited_nodes[current_node-1] = black; } return -1; }
you can further remove goal_f variable parameters , statements involving it. return value sufficient.
edit: problem in line of code
return dfsutil(search_key, x, childs.front(), visited_nodes, goal_f);
here function returning if goal had not been found. remaining (in queue) neighbors not getting visited. fix makes function return if goal has been reached. in fix, there "return -1" statement in end of function, indicates function finished without reaching goal.
for assesment of code logic, memory, , readability, , suggestions of best practices can post code here: https://codereview.stackexchange.com/
Comments
Post a Comment