Depth First Search 遍历功能
该函数采用当前节点索引的参数,邻接列表(在此示例中存储在向量的向量中)和布尔向量来跟踪已访问的节点。
void dfs(int node, vector<vector<int>>* graph, vector<bool>* visited) {
// check whether node has been visited before
if((*visited)[node])
return;
// set as visited to avoid visiting the same node twice
(*visited)[node] = true;
// perform some action here
cout << node;
// traverse to the adjacent nodes in depth-first manner
for(int i = 0; i < (*graph)[node].size(); ++i)
dfs((*graph)[node][i], graph, visited);
}