图的深度和广度优先算法
#include <stdio.h> #include <stdlib.h> #include <errno.h> #include <strings.h> #define N 5 #define M 10 typedef int datatype; typedef struct { datatype data[M]; int front,rear; }sequeue; sequeue * create() { sequeue * sq; if((sq = (sequeue *)malloc(sizeof(sequeue)))==NULL) { perror("malloc"); exit(-1); } sq ->front = sq->rear =0; return sq; } int isempty(sequeue * sq) { return (sq ->front) == (sq->rear); } void ensequeue(sequeue * sq,datatype data) { sq ->rear = (sq->rear+1)%M; sq ->data[sq->rear] = data; return ; } datatype desequeue(sequeue * sq) { datatype data; sq ->front = (sq->front+1)%M; data = sq->data[sq->front]; return data; } void visit(int v) { printf("V%d\n",v); } int firstadj(int matrix[][N],int v) //第一邻接点 { int i; for(i = 0;i < N;i++) { if(matrix[v][i] ==1) //矩阵特性,第一个不为0的点就是第一邻接点了 return i; } return -1; } int nextadj(int matrix[][N],int v,int u) //下一邻接点 { int i; for(i = u+1;i< N; i++) { if(matrix[v][i] == 1) return i; } return -1; } void DFS(int matrix[][N],int v,int visited[]) //深度优先搜索 { int u; visit(v); visited[v] = 1; u = firstadj(matrix,v); while(u >= 0) { if(visited[u] == 0) DFS(matrix,u,visited); u = nextadj(matrix,v,u); } } void BFS(int matrix[][N],int v,int visited[]) //广度优先搜索 { int u; sequeue *sq; sq = create(); visit(v); visited[v] = 1; ensequeue(sq,v); while(!isempty(sq)) { v = desequeue(sq); u = firstadj(matrix,v); while(u >= 0) { if(visited[u] == 0) { visit(u); visited[u] = 1; ensequeue(sq,u); } u = nextadj(matrix,v,u); } } } int main() { int i,j; int visited[N] = {0}; int matrix[N][N] = {{0}}; while(1) { scanf("%d,%d",&i,&j); if(i ==j) break; matrix[i][j] = matrix[j][i] = 1; //将无向图抽象成矩阵,5*5的矩阵 } printf("DFS:\n"); DFS(matrix,0,visited); printf("BFS:\n"); bzero(&visited,sizeof(visited)); //要将visited清空 BFS(matrix,0,visited); return 0; }