DFS,BFS
代码显示为输出连通集
算法时间复杂度:
采用邻接表存储图:DFS和BFS都为O(N+E)
采用邻接矩阵存储:DFS和BFS都为O(N^2);
数据结构设计
/// @brief 顶点
/// @param adjacencyList 邻接表
struct vertex
{
int id;
vector<int> adjacencyList;
};
vector<bool> visited(N,false);
vector<vertex> vertexList(N);
DFS
void dfs(int s,vector<bool>&visited,vector<int>&path,vector<vertex>vertexList)
{
vector<int> v = vertexList[s].adjacencyList;
for (int i=0; i<v.size(); ++i)
{
if(visited[v[i]]==false)
{
path.push_back(v[i]);
visited[v[i]] = true;
dfs(v[i], visited, path, vertexList);
}
}
}
BFS
void bfs(int s,vector<bool>&visited,vector<int>&path,vector<vertex>vertexList)
{
queue<int>q;
q.push(s);
while (!q.empty())
{
int cur = q.front();
q.pop();
vector<int> v = vertexList[cur].adjacencyList;
for (int i=0; i<v.size(); ++i)
{
if(visited[v[i]]==false)
{
path.push_back(v[i]);
visited[v[i]] = true;
q.push(v[i]);
}
}
}
}