第六课 DFS
伪代码(伪代码是用来记住算法的)
代码
View Code
#include <iostream> #include <vector> using namespace std; #define Max 100 int n, m; //n为点数,m为边数 int clk; //用于更新pre post int pre[Max], post[Max]; bool vis[Max]; vector<int> v[Max]; //邻接表 //开始访问x void pre_vis(int x) { pre[x] = clk; clk++; } //结束访问x void post_vis(int x) { post[x] = clk; clk++; } //从x开始搜索 void explore(int x) { vis[x] = true; pre_vis(x); for (int i = 0; i < v[x].size(); ++i) if (!vis[v[x][i]]) explore(v[x][i]); post_vis(x); } void dfs() { //init clk = 1; for (int i = 1; i <= n; ++i) vis[i] = false; //explore for (int i = 1; i <= n; ++i) if (!vis[i]) explore(i); //explore次数为连通分量次数 } int main() { cin >> n >> m; int a,b; for (int i = 0; i < m; ++i) { cin >> a >> b; v[a].push_back(b); } dfs(); }
转载请注明出处http://www.cnblogs.com/chenyg32/