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

#include

using namespace std;

const int N = 5;

int matrix[N][N] = {{ 0, 1, 1, 0, 0 },

{ 0, 0, 1, 0, 1 },

{ 0, 0, 0, 0, 0 },

{ 1, 1, 0, 0, 1 },

{ 0, 0, 1, 0, 0 }};

vector visited(N,false);

void DFS_Core(int start){

visited[start] = true;

cout<

for(auto i = 0;i < N;++i){

if(!visited[i] && matrix[start][i])

DFS_Core(i);

}

}

void DFS(){

for(auto i = 0;i < N;++i){

if(visited[i])

continue;

DFS_Core(i);

}

}

void BFS_Core(int start){

queue Q;

Q.push(start);

visited[start] = true;

while(!Q.empty()){

int front = Q.front();

cout<

Q.pop();

for(auto i = 0;i < N;++i){

if(!visited[i] && matrix[start][i]){

visited[i] = true;

Q.push(i);

}

}

}

}

void BFS(){

for(auto i = 0;i < N;++i){

if(visited[i])

continue;

BFS_Core(i);

}

}

int main(){

DFS();

cout<

for(auto i:visited)

i = false;

BFS();

return 0;

}

你可能感兴趣的:(图的深度优先和广度优先遍历)