图的深度优先遍历和广度优先遍历

dfs:

/*
  Coder
  Setting sail and crossing the sea,
  Can always going through the waves by wind.
*/
#include<iostream>
#include<cstdio>
#define MAXN 10010
using namespace std;

inline int read(){
   int s=0,w=1;
   char ch=getchar();
   while(ch<'0'||ch>'9'){if(ch=='-')w=-1;ch=getchar();}
   while(ch>='0'&&ch<='9') s=s*10+ch-'0',ch=getchar();
   return s*w;
}

int n,G[MAXN][MAXN];
bool vis[MAXN];

void dfs(int x){
	vis[x]=true;
	for(int i=1;i<=n;i++){
		if(G[x][i]&&!vis[i]) dfs(i);
	}
}

int main(){
	for(int i=1;i<=n;i++){
		if(!vis[i]){
			dfs(i);
		}
	}
	return 0;
}

对于有\(n\)个顶点,\(m\)条边的图采用邻接表表示时,进行\(dfs\)的时间复杂度为\(O(n+m)\),空间复杂度为\(O(n+m)\),进行\(bfs\)遍历时的时间复杂度为\(O(n+m)\),空间复杂度为\(O(n+m)\)

posted @ 2021-05-22 10:39  ICtiger  阅读(241)  评论(0)    收藏  举报