BFS和DFS是图的常见遍历算法。它们的时间复杂度取决于图的表示方法,可通过矩阵或邻接表来表示。
- 矩阵表示法
使用二维数组表示图。设图中节点数量为N,则矩阵的大小为N×N。
BFS时间复杂度为O(N^2),因为我们需要遍历矩阵中的每个元素。
以下是C++代码示例:
void BFS(vector>& graph, int start){
int n = graph.size();
vector visited(n, false);
queue q;
visited[start] = true;
q.push(start);
while(!q.empty()){
int node = q.front();
q.pop();
for(int i=0; i
DFS时间复杂度为O(N^2),因为在矩阵中搜索相邻的节点需要遍历整个行。
以下是C++代码示例:
void DFS(vector>& graph, int node, vector& visited){
visited[node] = true;
for(int i=0; i
- 邻接表表示法
使用数组和链表表示图。设图中节点数量为N,则数组的大小为N,链表的长度为边的数量。
BFS时间复杂度为O(N+E),其中E是边的数量。因为我们只需要遍历每个节点一次,并且在邻接表中找到所有相邻的节点。
以下是C++代码示例:
void BFS(vector>& graph, int start){
int n = graph.size();
vector visited(n, false);