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);
}